﻿#include "PolarCoordinateGraphWindow.h"
#include "PolarCoordinateGraphSidebarSettings.h"
#include "Curve2DPlotor.h"
#include "TextFileParser.h"
#include <QDomElement>
#include <QDomDocument>
#include <QDomAttr>
#include "PolarCoordinateSettingData.h"
#include "PolarCoordinateGraphSettingDialog.h"
#include "PolarGraph.h"
#include "DialogTracer2DSettings.h"
#include "PolarTracer.h"
#include "PolarAxisAngular.h"
#include "BaseModule/GlobalHelper.h"
#include "vtkTable.h"
#include "BaseWidget/IdaDialogMsg.h"
#include "BaseWidget/IWidgetSignal.h"
#include "DataManager/WindowTotalData.h"
#include <set>

namespace pst
{
    constexpr int kTracerTableWidgetOffsetX = 10;
    constexpr int kTracerTableWidgetOffsetY = 10;

    PolarCoordinateGraphWindow::PolarCoordinateGraphWindow(QWidget* parent, int windowId)
        : Graph2DWindowBase(parent),
          m_windowId(windowId)
        , m_polarCoordinateSetting(new PolarCoordinateSettingData(this))
        , m_polarCoordinateGraphCenterSettingData(new PolarCoordinateGraphCenterSettingData(this))
    {
        m_customPlot->plotLayout()->clear();

        m_tracerPropertyWidget = new PolarTracerTableWidget(m_customPlot);
        m_tracerPropertyWidget->installEventFilter(this);
        m_measureTableWidget = new PolarMeasureTableWidget(m_customPlot);
        m_measureTableWidget->installEventFilter(this);

        connect(m_tracerPropertyWidget, &TracerTableWidget::signal_removeMarkerSelect, m_customPlot, &Curve2DPlotor::removeMarkerSelect);
        connect(m_tracerPropertyWidget, &TracerTableWidget::signal_removeMarkerAll, m_customPlot, &Curve2DPlotor::removeMarkerAll);
        connect(m_tracerPropertyWidget, &TracerTableWidget::signal_disableTracer, m_customPlot, &Curve2DPlotor::disableTracer);
        connect(m_tracerPropertyWidget, &TracerTableWidget::signal_enableTracer, m_customPlot, &Curve2DPlotor::enableTracer);

        /*
         * 表格数据与图表初始化相同
         */
        Style2D_Title* style2D_Title = new Style2D_Title;
        style2D_Title->m_titleName = "极坐标图";
        m_polarCoordinateSetting->setTitle(style2D_Title);

        Style2D_Legend* style2D_Legend = new Style2D_Legend;
        style2D_Legend->m_legendFontSize = 20;
        m_polarCoordinateSetting->setLegend(style2D_Legend);

        //Style2D_Axis* style2D_Axis = new Style2D_Axis;
        //style2D_Axis->m_axisColor = QColor("#c8c8c8");
        //m_polarCoordinateSetting->setRadiusAxisDisplay(style2D_Axis);

        //Style2D_GridLine* style2D_GridLine = new Style2D_GridLine;
        //style2D_GridLine->m_mainGridLineStyle = 1;
        //m_polarCoordinateSetting->setGrid(style2D_GridLine);

        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData = m_polarCoordinateSetting;
        m_settings = new PolarCoordinateGraphSidebarSettings(this);
        m_settings->setMainWindowId(m_windowId);
        // 先连接信号和槽，然后设置m_settings的数值，以使其直接作用到m_customPlot
        initConnections();

        m_settings->updateUILayout(); // 布局
        /// @brief 测试代码结束

        // QSplitter* splitter = new QSplitter(Qt::Horizontal, this);
        // splitter->addWidget(m_customPlot);
        // splitter->addWidget(m_settings);
        // splitter->setSizes({3000, 1000});
        QHBoxLayout* layout = new QHBoxLayout(this);
        layout->setContentsMargins(0, 0, 0, 0);
        layout->setStretch(0, 1);
        layout->setStretch(1, 0);
        layout->addWidget(m_customPlot);
        layout->addWidget(m_settings);

        //m_customPlot->legend->setFillOrder(QCPLayoutGrid::foRowsFirst);
        //m_customPlot->legend->setWrap(34);
        // layout->addWidget(splitter);

        /*
         * m_customPlot信号导出marker数据
         */
        connect(m_customPlot, &Curve2DPlotor::signal_exportMarkerData, this, &PolarCoordinateGraphWindow::slot_exportMarkerData);
        connect(m_customPlot, &QCustomPlot::afterLayout, this, &PolarCoordinateGraphWindow::adjustLegendColumns);
    }

    PolarCoordinateGraphWindow::~PolarCoordinateGraphWindow()
    {
    }

    void PolarCoordinateGraphWindow::initConnections()
    {
        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_generateANewGraphCurve,
                this, &PolarCoordinateGraphWindow::slot_generateANewGraphCurve);

        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_chosenItemsChanged,
                this, &PolarCoordinateGraphWindow::slot_chosenItemsChanged);
        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_updateCurveData,
                this, &PolarCoordinateGraphWindow::slot_updateCurveData);
        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_updateCurveData,
                this, &PolarCoordinateGraphWindow::slot_updateName);

        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_legendTitleFontFamilyChanged,
                this, &PolarCoordinateGraphWindow::slot_legendTitleFontFamilyChanged);
        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_legendTitleFontSizeChanged,
                this, &PolarCoordinateGraphWindow::slot_legendTitleFontSizeChanged);

        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_renameGraph,
                this, &PolarCoordinateGraphWindow::slot_renameGraph);
        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_renameCheck,
                this, &PolarCoordinateGraphWindow::slot_renameCheck);

        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_getSidebarCurveDataSource, this, &PolarCoordinateGraphWindow::slot_getSidebarCurveDataSource);

        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_changeAllCurveVariableAxis, this, &PolarCoordinateGraphWindow::slot_changeAllCurveVariableAxis);

        connect(m_customPlot, &QCustomPlot::legendDoubleClick,
                [this](QCPLegend* legend, QCPAbstractLegendItem* item, QMouseEvent* event)
                {
                    slot_PolarLinePropertyShow(nullptr, 6);
                });

        connect(m_customPlot, &QCustomPlot::mouseDoubleClick, [this](QMouseEvent* event)
                {
                auto mMousePressPos = event->pos();
                auto angularAxis = qobject_cast<QCPPolarAxisAngular*>(m_customPlot->plotLayout()->element(1, 0));

                // determine layerable under the cursor (this event is called instead of the second press event in a double-click):
                QList<QVariant> details;
                QList<QCPLayerable*> result;
                QList<QCPLayer*> mLayers;
                mLayers.append(m_customPlot->layer("background"));
                mLayers.append(m_customPlot->layer("grid"));
                mLayers.append(m_customPlot->layer("main"));
                mLayers.append(m_customPlot->layer("axes"));
                mLayers.append(m_customPlot->layer("legend"));
                mLayers.append(m_customPlot->layer("overlay"));
                for (int layerIndex = mLayers.size() - 1; layerIndex >= 0; --layerIndex)
                {
                    if (mLayers.at(layerIndex) == nullptr)
                    {
                        continue;
                    }
                    const QList<QCPLayerable*> layerables = mLayers.at(layerIndex)->children();
                    for (int i = layerables.size() - 1; i >= 0; --i)
                    {
                        if (!layerables.at(i)->realVisibility())
                            continue;
                        QVariant d;
                        double dist = layerables.at(i)->selectTest(mMousePressPos, false, &d);
                        if (dist >= 0 && dist < m_customPlot->selectionTolerance())
                        {
                            result.append(layerables.at(i));
                            details.append(d);
                        }
                    }
                }
                QList<QCPLayerable*> candidates = result;

                // emit specialized object double click signals:
                if (!candidates.isEmpty())
                {
                    if (PolarGraph* polarGraph = qobject_cast<PolarGraph*>(candidates.first()))
                    {
                        m_doubleClickPlottable = polarGraph;
                        slot_PolarLinePropertyShow(polarGraph, 7);
                    }
                    else if (QCPPolarAxisAngular* ax = qobject_cast<QCPPolarAxisAngular*>(candidates.first()))
                    {
                        slot_PolarLinePropertyShow(nullptr, 0);
                    }
                    else if (QCPTextElement* ax = qobject_cast<QCPTextElement*>(candidates.first()))
                    {
                        slot_PolarLinePropertyShow(nullptr, 5);
                    }
                    //else if (QCPLegend* ax = qobject_cast<QCPLegend*>(candidates.first()))
                    //{
                    //    slot_PolarLinePropertyShow(nullptr, 6);
                    //}
                } });

        connect(m_customPlot, &QCustomPlot::itemDoubleClick, [this](QCPAbstractItem* item, QMouseEvent* event)
                {
                        auto tracerPropertyWidget = m_tracerPropertyWidget;
                        for (int i = 0; i < tracerPropertyWidget->rowCount(); ++i)
                        {
                            auto tracer = tracerPropertyWidget->item(i, 0)->data(QVariant::UserType).value< LineChartTracer* >();
                            if (tracer == item || tracer->GetLabel() == item || tracer->GetArrow() == item)
                            {
                                slot_TracerPropertyShow(tracer);
                                return;
                            }
                        } });

        auto listView = m_settings->getCurveNameListView();
        if (listView != nullptr)
        {
            connect(listView, &QListView::doubleClicked, [this](const QModelIndex& index)
                    {
                                    auto model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
                                    auto item = model->itemFromIndex(index);
                                    PolarGraph* polarGraph = qobject_cast<PolarGraph*>(getCurveInfoByItem(item)->getCurveLineAddress());
                                    if (m_customPlot->xAxis == nullptr)
                                    {
                                        if (polarGraph != nullptr)
                                        {
                                            m_doubleClickPlottable = polarGraph;
                                            slot_PolarLinePropertyShow(polarGraph, 7);
                                        }
                                    } });
        }

        connect(m_tracerPropertyWidget, &PolarTracerTableWidget::signal_doubleClicked,
                this, &PolarCoordinateGraphWindow::slot_TracerPropertyShow);

        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_showHideItemActor,
                this, &PolarCoordinateGraphWindow::slot_showHideItemActor);

        // ListView的右键菜单
        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_removeSelectedGraph,
                this, &PolarCoordinateGraphWindow::slot_removeSelectedGraph);

        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_copySelectedGraph,
                this, &PolarCoordinateGraphWindow::slot_copySelectedGraph);

        connect(m_settings, &PolarCoordinateGraphSidebarSettings::signal_deleteAllCurve,
                this, &PolarCoordinateGraphWindow::slot_removeAlldGraph);

        // 视图中的右键菜单
        connect(m_customPlot, &Curve2DPlotor::signal_updateSelectedGraph,
                this, &PolarCoordinateGraphWindow::slot_updateSelectedGraph);

        connect(m_customPlot, &Curve2DPlotor::signal_removeSelectedGraph,
                this, &PolarCoordinateGraphWindow::slot_removeSelectedGraph);

        connect(m_customPlot, &Curve2DPlotor::signal_removeAlldGraph,
                this, &PolarCoordinateGraphWindow::slot_removeAlldGraph);

        // 标记点
        connect(m_customPlot, &Curve2DPlotor::signal_addTracer,
                this, &PolarCoordinateGraphWindow::slot_AddTracer);

        connect(m_customPlot, &Curve2DPlotor::mouseMove,
                this, &PolarCoordinateGraphWindow::slot_ShowPreviewTracer);

        connect(m_customPlot, &Curve2DPlotor::signal_removeSelectedTracer,
                this, &PolarCoordinateGraphWindow::slot_removeSelectedTracer_script);

        connect(m_customPlot, &Curve2DPlotor::signal_removeAlldTracer,
                this, &PolarCoordinateGraphWindow::slot_removeAllTracer_script);

        connect(m_customPlot, &QCustomPlot::beforeReplot, this, &PolarCoordinateGraphWindow::slot_updateBeamBandwidthProperty);

        connect(m_customPlot, &QCustomPlot::afterReplot, m_tracerPropertyWidget, &PolarTracerTableWidget::slot_updateTracerProperty);
        connect(m_customPlot, &QCustomPlot::selectionChangedByUser, m_tracerPropertyWidget, &PolarTracerTableWidget::slot_updateTracerChange);
        connect(m_customPlot, &QCustomPlot::selectionChangedByUser, m_measureTableWidget, &PolarMeasureTableWidget::slot_updateTracerChange);
        connect(m_customPlot, &QCustomPlot::beforeReplot, m_measureTableWidget, &PolarMeasureTableWidget::slot_updateTracerProperty);

        connect(m_customPlot, &Curve2DPlotor::signal_updateSelectedGraph, this, &PolarCoordinateGraphWindow::slot_updateSelectedGraphState);

        connect(m_customPlot, &Curve2DPlotor::signal_renameGraph, this, &PolarCoordinateGraphWindow::slot_renameGraph);

        connect(IWidgetSignalInstance, &BaseWidget::IWidgetSignal::signal_closeTree, this, &PolarCoordinateGraphWindow::slot_closeTree);
        connect(IBaseSignalInstance, &BaseWidget::IWidgetSignal::signal_savePolarCoordinateGraphMainSettingData, this, &PolarCoordinateGraphWindow::slot_polarCoordinateGraphSaveMainSettingData);
    }

    void PolarCoordinateGraphWindow::adjustLegendColumns()
    {
        if (m_customPlot->legend == nullptr)
        {
            return;
        }
        if (!m_customPlot->legend->visible())
        {
            return;
        }

        auto legend = m_customPlot->legend;
        QFontMetrics fm(legend->font());
        auto iconSize = legend->iconSize();
        // 让图标高度也达到文字高度
        legend->setIconSize(QSize(fm.height() * 32. / 18. * 1.3, fm.height() * 1.3));
        int rowSpacing = legend->rowSpacing();           // 行间距
        int itemHeight = qMax(iconSize.height(), fm.height()) + rowSpacing /*+ iconPad*/;
        int availH = m_customPlot->height() - 50;
        int maxPerCol = qMax(1, availH / itemHeight);

        legend->setFillOrder(QCPLegend::foRowsFirst);
        legend->setWrap(maxPerCol);
        m_customPlot->replot();
    }

    bool PolarCoordinateGraphWindow::eventFilter(QObject* watched, QEvent* event)
    {
        if (event->type() == QEvent::Wheel && (watched == m_tracerPropertyWidget || watched == m_measureTableWidget))
        {
            event->accept();
            return true;
        }
        return false;
    }

    void PolarCoordinateGraphWindow::setWindowID(int windowID)
    {
        m_windowId = windowID;
    }
    int PolarCoordinateGraphWindow::getWindowID() const
    {
        return m_windowId;
    }
    void PolarCoordinateGraphWindow::setWindowUniversalID(int windowUniversalID)
    {
        m_windowUniversalID = windowUniversalID;
        m_settings->setWindowUniversalID(windowUniversalID);
    }
    int PolarCoordinateGraphWindow::getWindowUniversalID() const
    {
        return m_windowUniversalID;
    }

    QDomElement& PolarCoordinateGraphWindow::writeToProjectFile(QDomDocument* doc, QDomElement* element, bool isdiso)
    {
        QDomElement _PolarCoordinateGraphWindowDataRoot = doc->createElement("GraphWindow");
        QDomAttr _WindowUniversalIDattr = doc->createAttribute("WindowUniversalID");
        _WindowUniversalIDattr.setValue(QString::number(m_windowUniversalID));
        _PolarCoordinateGraphWindowDataRoot.setAttributeNode(_WindowUniversalIDattr);
        QDomAttr _idattr = doc->createAttribute("WindowID");
        _idattr.setValue(QString::number(m_windowId));
        _PolarCoordinateGraphWindowDataRoot.setAttributeNode(_idattr);
        QDomAttr typeattr = doc->createAttribute("WindowType");
        typeattr.setValue("PolarCoordinateGraphWindow");
        _PolarCoordinateGraphWindowDataRoot.setAttributeNode(typeattr);

        GlobalHelperInstance->createDomElement(doc, &_PolarCoordinateGraphWindowDataRoot, "AutoRadialRescaleAxes", QString::number(m_autoRadialRescaleAxes));
        GlobalHelperInstance->createDomElement(doc, &_PolarCoordinateGraphWindowDataRoot, "GraphIndex", QString::number(m_graphIndex));
        GlobalHelperInstance->createDomElement(doc, &_PolarCoordinateGraphWindowDataRoot, "TracerIndex", QString::number(m_tracerIndex));

        element->appendChild(_PolarCoordinateGraphWindowDataRoot);
        if (m_polarCoordinateSetting != nullptr)
            m_polarCoordinateSetting->writeToProjectFile(doc, &_PolarCoordinateGraphWindowDataRoot, isdiso);
        // m_curveMap存了所有曲线
        for (auto _curveInfoPair : m_curveMap)
        {
            auto _item = _curveInfoPair.first;
            _curveInfoPair.second->setIsCurveVisible(_item->checkState());
            _curveInfoPair.second->writeToProjectFile(doc, &_PolarCoordinateGraphWindowDataRoot, GraphType::PolarGraph, isdiso);
        }
        if (m_tracerPropertyWidget != nullptr)
            m_tracerPropertyWidget->writeToProjectFile(doc, &_PolarCoordinateGraphWindowDataRoot, GraphType::PolarGraph, isdiso);
        if (m_measureTableWidget != nullptr)
            m_measureTableWidget->writeToProjectFile(doc, &_PolarCoordinateGraphWindowDataRoot, isdiso);

        return _PolarCoordinateGraphWindowDataRoot;
    }

    void PolarCoordinateGraphWindow::readFromProjectFile(QDomElement* element, bool isdiso)
    {
        m_windowUniversalID = element->attribute("WindowUniversalID").toInt();
        int id = element->attribute("WindowID").toInt();
        m_windowId = id;

        QDomNodeList AutoRadialRescaleAxesList = element->elementsByTagName("AutoRadialRescaleAxes");
        m_autoRadialRescaleAxes = (bool)AutoRadialRescaleAxesList.at(0).toElement().text().toInt();
        QDomNodeList GraphIndexList = element->elementsByTagName("GraphIndex");
        m_graphIndex = GraphIndexList.at(0).toElement().text().toInt();
        QDomNodeList XAxisRangeList = element->elementsByTagName("TracerIndex");
        m_tracerIndex = XAxisRangeList.at(0).toElement().text().toInt();


        auto _centerSettingNodeList = element->elementsByTagName("PolarCoordinateSettingData");
        m_polarCoordinateSetting->readFromProjectFile(&_centerSettingNodeList.at(0).toElement(), isdiso);
        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData = m_polarCoordinateSetting;

        auto _infosNodeList = element->elementsByTagName("InfomationCurve2DBasical");
        auto _infosCount = _infosNodeList.count();
        if (_infosCount == 0)
            return;
        for (int i = 0; i < _infosCount; i++)
        {
            auto _info = Info2DPointer::create();
            _info->readFromProjectFile(&_infosNodeList.at(i).toElement(), GraphType::PolarGraph, isdiso);
            if (_info->getProjectTreeSourceItem() == nullptr)
                continue;
            m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty = _info->getCurvePropertyData();
            _info->setPolarGraphCenterSettingData(m_polarCoordinateGraphCenterSettingData);
            addNewGraphByOpenProject(_info, _info->getCurveName());

            // 更新侧边栏和曲线数据
            auto model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
            auto _curveSiderBarItem = this->getItemFromCurveInfo(_info);
            if (_curveSiderBarItem != nullptr)
            {
                auto _itemIndex = model->indexFromItem(_curveSiderBarItem);
                emit IBaseSignalInstance->signal_polarCoordinateGraphSidebarCurveNameClicked(m_windowId, {_itemIndex.row()});
                if (_info->getIsNormalized() || _info->getIsDB())
                    emit IBaseSignalInstance->signal_polarCoordinateGraphSidebarDataOperationChanged(m_windowId, _info->getIsNormalized(), _info->getIsDB());
            }
            slot_ChangePolarLineProperty(m_windowUniversalID, _info->getInformationID(), _info, false);
        }
        auto _TracerTableWidgetNodeList = element->elementsByTagName("PolarTracerTableWidget");
        m_tracerPropertyWidget->readFromProjectFile(&_TracerTableWidgetNodeList, m_customPlot, GraphType::PolarGraph, isdiso);
        if (m_tracerPropertyWidget->rowCount() > 0)
        {
            setTracerTableWidgetVisible(m_tracerPropertyWidget, true);
        }
        auto _MeasureTableWidgetNodeList = element->elementsByTagName("PolarMeasureTableWidget");
        m_measureTableWidget->readFromProjectFile(&_MeasureTableWidgetNodeList, m_customPlot, isdiso);
        if (m_measureTableWidget->rowCount() > 0)
        {
            setTracerTableWidgetVisible(m_measureTableWidget, true);
        }
        // 最后刷新标记的显示隐藏
        for (auto curvePair : m_curveMap)
        {
            auto _checkState = curvePair.second->getIsCurveVisible();
            if (!_checkState) // 默认可见，则不用设置
            {
                auto _curveSiderBarItem = getItemFromCurveInfo(curvePair.second);
                _curveSiderBarItem->model()->blockSignals(true);
                _curveSiderBarItem->setData(_checkState, Qt::UserRole);
                _curveSiderBarItem->model()->blockSignals(false);
                _curveSiderBarItem->setCheckState((Qt::CheckState)_checkState);
                slot_showHideItemActor(_curveSiderBarItem);
            }
        }
    }

    QStandardItem* PolarCoordinateGraphWindow::addNewGraph(Info2DPointer& info, const QString& name)
    {
        const auto& xData = info->getXData().second;
        const auto& yData = info->getYData().second;

        PolarGraph* graph = new PolarGraph(m_angularAxis, m_angularAxis->radialAxis());
        connect(graph, &PolarGraph::signal_selectionChanged,
                this, &PolarCoordinateGraphWindow::slot_polarGraphSelectionChanged);
        connect(graph, &PolarGraph::signal_legendItemSelectionChanged,
                this, &PolarCoordinateGraphWindow::slot_polarGraphSelectionChanged);
        // connect(graph, &PolarGraph::signal_mouseDoubleClicked, this, [this](QMouseEvent* event, const QVariant& details)
        //         {
        //         PolarGraph* polarGraph = qobject_cast<PolarGraph*>(sender());
        //         m_doubleClickPlottable = polarGraph;
        //         slot_PolarLinePropertyShow(polarGraph, 7);
        // });

        // 设置颜色
        auto index = m_graphs.size() % m_colorList.size();
        auto color = m_colorList.at(index);
        QPen pen;
        pen.setWidth(2);
        pen.setColor(color);
        graph->setPen(pen);
        m_graphs.append(graph);
        graph->setName(name);
        info->setCurveLineAddress(graph); // 记录曲线地址
        if (!GlobalHelperInstance->getIsOpenProject())
        {
            info->setCurveName(name);
            info->setInformationID(WindowTotalDataInstance->getGraph2DInformationMaxID());
        }
        WindowTotalDataInstance->appendInfomationCurve2DBasical(info);
        // 添加曲线名字
        QStandardItem* item = m_settings->addCurveToList(name);
        // item->setCheckState(Qt::Checked);
        // m_curveMap[item] = info; // 记录下来以备查找
        addCurveItemInfoPair(item, info);
        info->setSidebarItem(item);

        // 定义一个临时 lambda 函数，用于归一化角度到 [-180, 180]
        auto normalizeAngle = [](double angle) -> double
        {
            // 先使用 std::fmod 计算 angle 除以 360 后的余数
            double ret = std::fmod(angle, 360.0);
            // 注意：std::fmod 对于负数的余数保留负号
            // 如果余数大于 180，则减去 360，使其进入 [-180, 180] 内
            if (ret > 180.0)
            {
                ret -= 360.0;
            }
            // 如果余数小于 -180，则加上 360
            else if (ret < -180.0)
            {
                ret += 360.0;
            }
            return ret;
        };

        for (int i = 0; i < xData.size(); ++i)
        {
            auto x = xData.at(i);
            // graph->addData(normalizeAngle(xData.at(i)), yData.at(i));
            graph->addData(xData.at(i), yData.at(i));

            //std::cout << i << " orignal" << xData.at(i) << "  normalized " << normalizeAngle(xData.at(i)) << " value  " << yData.at(i) << std::endl;
        }
        auto dataProperty = new Style2D_DataProperty(this);
        dataProperty->m_dataLineColor = color;
        dataProperty->m_symbolColor = color;

        if (info->getXData().second.size() == 1)
        {
            auto scatterStyle = graph->scatterStyle();
            scatterStyle.setShape(QCPScatterStyle::ssDisc);
            scatterStyle.setPen(color);
            graph->setScatterStyle(scatterStyle);

            dataProperty->m_isDisplaySymbol = true;
            dataProperty->m_symbolStyle = 4;
        }
        m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty = dataProperty;
        info->setPolarGraphCenterSettingData(m_polarCoordinateGraphCenterSettingData);
        info->setCurvePropertyData(dataProperty);

        if (m_autoRadialRescaleAxes)
        {
            // graph->rescaleAxes(true);
            graph->rescaleValueAxis();
            m_angularAxis->radialAxis()->rescale(true);
        }

        return item;
    }
    QStandardItem* PolarCoordinateGraphWindow::addNewGraphByOpenProject(Info2DPointer& info, const QString& name)
    {
        if (!m_angularAxis)
        {
            // m_customPlot->plotLayout()->clear();
            QCPTextElement* title = new QCPTextElement(m_customPlot, "极坐标图", QFont("sans", 10, QFont::Bold));
            m_customPlot->plotLayout()->addElement(0, 0, title);
            m_angularAxis = new PolarAxisAngular(m_customPlot);
            m_customPlot->plotLayout()->addElement(1, 0, m_angularAxis);
            QCPLegend* legend = new QCPLegend();
            m_customPlot->legend = legend;
            legend->setParent(m_customPlot);
            legend->setVisible(true);
            QCPLayoutInset* insetLayout = new QCPLayoutInset;
            m_customPlot->plotLayout()->addElement(1, 1, insetLayout);
            insetLayout->addElement(legend, Qt::AlignRight | Qt::AlignTop);
            insetLayout->setMargins(QMargins(0, 0, 10, 0));
            m_customPlot->plotLayout()->setColumnStretchFactor(0, 999);
            legend->setLayer(QLatin1String("legend"));
            legend->setBrush(QBrush(QColor(255, 255, 255, 200))); // 设置背景颜色
            legend->setBorderPen(QPen(Qt::black));                //
            InitializeResultWindowStyle();

            m_angularAxis->setRangeDrag(false);
            m_angularAxis->setTickLabelMode(QCPPolarAxisAngular::lmUpright);
            m_angularAxis->setRange(-180, 180);

            m_angularAxis->radialAxis()->setTickLabelMode(QCPPolarAxisRadial::lmUpright);
            m_angularAxis->radialAxis()->setTickLabelRotation(0);
            QColor _color = QColor("#c8c8c8");
            m_angularAxis->radialAxis()->setBasePen(QPen(QColor("#000"), 1, Qt::SolidLine));
            m_angularAxis->radialAxis()->setTickPen(QPen(QColor("#000"), 1, Qt::SolidLine));
            m_angularAxis->radialAxis()->setSubTickPen(QPen(QColor("#000"), 1, Qt::SolidLine));
            // m_angularAxis->radialAxis()->setAngle(45);
            m_angularAxis->grid()->setAngularPen(QPen(_color, 1, Qt::DotLine));
            m_angularAxis->grid()->setRadialPen(QPen(_color, 1, Qt::DotLine));
            m_angularAxis->grid()->setRadialSubGridPen(QPen(_color, 1, Qt::DotLine));
            m_angularAxis->grid()->setRadialZeroLinePen(QPen(_color, 1, Qt::DotLine));
            m_angularAxis->grid()->setSubGridType(QCPPolarGrid::gtAll);
            m_angularAxis->setRangeZoomFactor(0.95);
            m_customPlot->setPolarAxisAngular(m_angularAxis);
        }

        const auto& xData = info->getXData().second;
        const auto& yData = info->getYData().second;

        PolarGraph* graph = new PolarGraph(m_angularAxis, m_angularAxis->radialAxis());
        connect(graph, &PolarGraph::signal_selectionChanged,
                this, &PolarCoordinateGraphWindow::slot_polarGraphSelectionChanged);
        connect(graph, &PolarGraph::signal_legendItemSelectionChanged,
                this, &PolarCoordinateGraphWindow::slot_polarGraphSelectionChanged);

        // 设置颜色
        auto index = m_graphs.size() % m_colorList.size();
        auto color = m_colorList.at(index);
        QPen pen;
        pen.setWidth(2);
        pen.setColor(color);
        graph->setPen(pen);
        m_graphs.append(graph);
        graph->setName(name);
        info->setCurveLineAddress(graph); // 记录曲线地址
        WindowTotalDataInstance->appendInfomationCurve2DBasical(info);
        // 添加曲线名字
        QStandardItem* item = m_settings->addCurveToList(name);
        addCurveItemInfoPair(item, info);
        info->setSidebarItem(item);

        // 定义一个临时 lambda 函数，用于归一化角度到 [-180, 180]
        auto normalizeAngle = [](double angle) -> double
        {
            // 先使用 std::fmod 计算 angle 除以 360 后的余数
            double ret = std::fmod(angle, 360.0);
            // 注意：std::fmod 对于负数的余数保留负号
            // 如果余数大于 180，则减去 360，使其进入 [-180, 180] 内
            if (ret > 180.0)
            {
                ret -= 360.0;
            }
            // 如果余数小于 -180，则加上 360
            else if (ret < -180.0)
            {
                ret += 360.0;
            }
            return ret;
        };

        for (int i = 0; i < xData.size(); ++i)
        {
            auto x = xData.at(i);
            graph->addData(xData.at(i), yData.at(i));
        }

        if (info->getXData().second.size() == 1)
        {
            auto scatterStyle = graph->scatterStyle();
            scatterStyle.setShape(QCPScatterStyle::ssDisc);
            scatterStyle.setPen(color);
            graph->setScatterStyle(scatterStyle);
        }

        if (m_autoRadialRescaleAxes)
        {
            graph->rescaleValueAxis();
            m_angularAxis->radialAxis()->rescale(true);
        }
        m_addCurveInfo.append(info);
        QCoreApplication::processEvents(); // 让 UI 有机会更新,防止获取高度axisRect()->rect().height()失败
        QTimer::singleShot(0, this, [=]() {
            adjustLegendColumns();
            });

        slot_adaptiveRange();

        return item;
    }

    void PolarCoordinateGraphWindow::addGraph2D(Info2DPointer& info)
    {
        if (!m_angularAxis)
        {
            // m_customPlot->plotLayout()->clear();
            QCPTextElement* title = new QCPTextElement(m_customPlot, "极坐标图", QFont("sans", 10, QFont::Bold));
            m_customPlot->plotLayout()->addElement(0, 0, title);
            m_angularAxis = new PolarAxisAngular(m_customPlot);
            m_customPlot->plotLayout()->addElement(1, 0, m_angularAxis);
            QCPLegend* legend = new QCPLegend();
            m_customPlot->legend = legend;
            legend->setParent(m_customPlot);
            legend->setVisible(true);
            QCPLayoutInset* insetLayout = new QCPLayoutInset;
            m_customPlot->plotLayout()->addElement(1, 1, insetLayout);
            insetLayout->addElement(legend, Qt::AlignRight | Qt::AlignTop);
            insetLayout->setMargins(QMargins(0, 0, 10, 0));
            m_customPlot->plotLayout()->setColumnStretchFactor(0, 999);
            legend->setLayer(QLatin1String("legend"));
            legend->setBrush(QBrush(QColor(255, 255, 255, 200))); // 设置背景颜色
            legend->setBorderPen(QPen(Qt::black));                //
            InitializeResultWindowStyle();

            m_angularAxis->setRangeDrag(false);
            m_angularAxis->setTickLabelMode(QCPPolarAxisAngular::lmUpright);
            m_angularAxis->setRange(-180, 180);

            m_angularAxis->radialAxis()->setTickLabelMode(QCPPolarAxisRadial::lmUpright);
            m_angularAxis->radialAxis()->setTickLabelRotation(0);
            QColor _color = QColor("#c8c8c8");
            m_angularAxis->radialAxis()->setBasePen(QPen(QColor("#000"), 1, Qt::SolidLine));
            m_angularAxis->radialAxis()->setTickPen(QPen(QColor("#000"), 1, Qt::SolidLine));
            m_angularAxis->radialAxis()->setSubTickPen(QPen(QColor("#000"), 1, Qt::SolidLine));
            // m_angularAxis->radialAxis()->setAngle(45);
            m_angularAxis->grid()->setAngularPen(QPen(_color, 1, Qt::DotLine));
            m_angularAxis->grid()->setRadialPen(QPen(_color, 1, Qt::DotLine));
            m_angularAxis->grid()->setRadialSubGridPen(QPen(_color, 1, Qt::DotLine));
            m_angularAxis->grid()->setRadialZeroLinePen(QPen(_color, 1, Qt::DotLine));
            m_angularAxis->grid()->setSubGridType(QCPPolarGrid::gtAll);
            m_angularAxis->setRangeZoomFactor(0.95);

            // 修改半径轴精度
            m_angularAxis->radialAxis()->setNumberFormat("f");
            m_angularAxis->radialAxis()->setNumberPrecision(6);

            m_customPlot->setPolarAxisAngular(m_angularAxis);


        }
        //QString name = "曲线_" + QString::number(++m_graphIndex);
        QString name = info->getCurveName().remove(QRegularExpression("\\[.*?]$"));

        if (name.isEmpty())
        {
            name = "曲线";
        }
        QString incrementName = autoIncrementName(name);
        info->setCurveName(incrementName);
        QStandardItem* item = addNewGraph(info, incrementName);

        // m_customPlot->replot();

        // slot_updateCurveData({ item }, info);
        slot_adaptiveRange();
        slot_updateName();
        m_addCurveInfo.append(info);
        QCoreApplication::processEvents(); // 让 UI 有机会更新,防止获取高度axisRect()->rect().height()失败
        QTimer::singleShot(0, this, [=]() {
            adjustLegendColumns();
            });
    }
    void PolarCoordinateGraphWindow::InitializeResultWindowStyle()
    {
        if (m_angularAxis != nullptr)
        {
            // x

            auto basePenX = m_angularAxis->basePen();
            basePenX.setWidthF(1);
            m_angularAxis->setBasePen(basePenX);
            auto tickLabelFontX = m_angularAxis->tickLabelFont();
            tickLabelFontX.setPointSize(16);
            m_angularAxis->setTickLabelFont(tickLabelFontX);

            // y
            auto basePenY = m_angularAxis->radialAxis()->basePen();
            //basePenY.setColor(Qt::black);
            basePenY.setWidthF(1);
            m_angularAxis->radialAxis()->setBasePen(basePenY);
            auto tickLabelFontY = m_angularAxis->radialAxis()->tickLabelFont();
            tickLabelFontY.setPointSize(16);
            m_angularAxis->radialAxis()->setTickLabelFont(tickLabelFontY);

            // title
            auto title = qobject_cast<QCPTextElement*>(m_customPlot->plotLayout()->element(0, 0));
            if (title != nullptr)
            {
                auto fontTitle = title->font();
                fontTitle.setPointSize(20);
                title->setFont(fontTitle);
            }

            auto fontLegend = m_customPlot->legend->font();
            fontLegend.setPointSize(20);
            m_customPlot->legend->setFont(fontLegend);
            auto fontLegendSelected = m_customPlot->legend->selectedFont();
            fontLegendSelected.setPointSize(20);
            m_customPlot->legend->setSelectedFont(fontLegendSelected);
            auto borderPen = m_customPlot->legend->borderPen();
            borderPen.setWidthF(1);
            m_customPlot->legend->setBorderPen(borderPen);

            QPen radialPen = m_angularAxis->grid()->radialPen();
            radialPen.setWidthF(1);
            m_angularAxis->grid()->setRadialPen(radialPen);

            QPen radialSubGridPen = m_angularAxis->grid()->radialSubGridPen();
            radialSubGridPen.setWidthF(1);
            m_angularAxis->grid()->setRadialSubGridPen(radialSubGridPen);

            QPen radialZeroLinePen = m_angularAxis->grid()->radialZeroLinePen();
            radialZeroLinePen.setWidthF(1);
            m_angularAxis->grid()->setRadialZeroLinePen(radialZeroLinePen);
        }
    }

    QStandardItem* PolarCoordinateGraphWindow::copyGraph(Info2DPointer& info, const QString& curveName)
    {
        QStandardItem* item = nullptr;
        PolarGraph* graphToBeCopied = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
        if (!graphToBeCopied)
        {
            qWarning() << "unexpected error: the graph to be copied is null";
            return nullptr;
        }

        /*int graphIdex = 1;
        QString name = QString("%1_%2").arg(curveName).arg(graphIdex);
        QList<QString> existingNames;
        for (auto curvePair : m_curveMap)
        {
            existingNames.append(slot_getCurveName(curvePair.first, curvePair.second));
        }

        while (existingNames.contains(name))
        {
            ++graphIdex;
            name = QString("%1_%2").arg(curveName).arg(graphIdex);
        }*/

        QString name = autoIncrementName(curveName);

        // info.getYDataPointer()->first = name;
        item = addNewGraph(info, name);
        return item;

        // m_customPlot->replot();
    }
    QString PolarCoordinateGraphWindow::autoIncrementName(QString name)
    {
        QString pattern = QString("^%1_([0-9]+)$").arg(QRegularExpression::escape(name));
        QRegularExpression reg(pattern);

        QListView* listView = m_settings->getCurveNameListView();
        QAbstractItemModel* model = listView->model();

        if (model)
        {
            int maxNumber = 0;
            for (int row = 0; row < model->rowCount(); ++row)
            {
                QModelIndex index = model->index(row, 0); // 第0列
                QString text = model->data(index, Qt::DisplayRole).toString();
                QString str = text.remove(QRegularExpression("\\[.*?]$"));
                QRegularExpressionMatch match = reg.match(str);
                if (match.hasMatch())
                {
                    QString numberStr = match.captured(1);
                    int number = numberStr.toInt();
                    maxNumber = std::max(maxNumber, number);
                }
            }
            maxNumber++;
            return QString("%1_%2")
                .arg(name)
                .arg(QString::number(maxNumber));
        }
        else
        {
            return name;
        }
    }
    void PolarCoordinateGraphWindow::slot_adaptiveRange()
    {
        auto* angularAxis = qobject_cast<QCPPolarAxisAngular*>(m_customPlot->plotLayout()->element(1, 0));

        // if (m_autoRadialRescaleAxes)//自动范围
        //{
        double globalMin = std::numeric_limits<double>::max();
        double globalMax = std::numeric_limits<double>::lowest();
        int foundVisibleGraph = 0;
        if (angularAxis == nullptr)
        {
            return;
        }
        // 遍历所有曲线

        for (auto& graph : m_graphs)
        {
            if (QCPPolarGraph* g = dynamic_cast<QCPPolarGraph*>(graph))
            {
                if (!g->visible())
                {
                    continue;
                }
                auto dataContainer = g->data();
                for (auto it = dataContainer->constBegin(); it != dataContainer->constEnd(); ++it)
                {
                    double r = it->value; // 在极坐标中，value通常代表半径
                    if (r < globalMin)
                        globalMin = r;
                    if (r > globalMax)
                        globalMax = r;
                }
                ++foundVisibleGraph;
            }
        }

        if (foundVisibleGraph > 0)
        {
            QVector<double> v;
            angularAxis->radialAxis()->ticker()->generate(QCPRange(globalMin, globalMax), m_customPlot->locale(), 'g', 6, v, nullptr, nullptr);
            double num = 0.0;
            if (v.size() < 2)
            {
                num = 0.5;
            }
            else if (foundVisibleGraph > 1)
            {
                num = v.at(1) - v.at(0);
            }
            angularAxis->radialAxis()->setRange(globalMin - num, globalMax + num);
        }
        else
        {
            angularAxis->radialAxis()->setRange(0, 1);
        }
        //}
        // else //手动范围
        //{
        //    //auto upper = m_angularAxis->radialAxis()->range().upper;
        //    //auto lower = m_angularAxis->radialAxis()->range().lower;
        //    //angularAxis->radialAxis()->setRange(lower, upper);
        //}

        m_customPlot->replot();
    }

    // 放大
    void PolarCoordinateGraphWindow::slot_amplify()
    {
        const double factor = m_angularAxis->rangeZoomFactor();
        if (m_angularAxis)
        {
            // m_angularAxis->scaleRange(factor);

            QList<QCPPolarAxisRadial*> radialAxes = m_angularAxis->radialAxes();
            for (QCPPolarAxisRadial* ax : radialAxes)
            {
                ax->scaleRange(factor);
            }

            m_customPlot->replot();
        }
    }

    // 缩小
    void PolarCoordinateGraphWindow::slot_minification()
    {
        const double factor = 2 - m_angularAxis->rangeZoomFactor();
        if (m_angularAxis)
        {
            // m_angularAxis->scaleRange(factor);

            QList<QCPPolarAxisRadial*> radialAxes = m_angularAxis->radialAxes();
            for (QCPPolarAxisRadial* ax : radialAxes)
            {
                ax->scaleRange(factor);
            }

            m_customPlot->replot();
        }
    }

    // 设置框中选中的曲线发生改变->根据曲线信息更新m_settings
    void PolarCoordinateGraphWindow::slot_chosenItemsChanged(const QList<QStandardItem*>& itemList)
    {
        QList<Info2DPointer> curInfoList;
        for (const auto& i : itemList)
        {
            if (!judgmentItemInfoPairIsExist(i))
            {
                // todo 警告
                continue;
            }
            curInfoList.append(getCurveInfoByItem(i));
        }

        if (curInfoList.isEmpty())
        {
            // 折叠控制面板
            m_settings->hideCurvePropertylPanel();
        }
        else
        {
            // 各个曲线信息的交集
            Info2DPointer commonInfo = Info2DPointer::create();
            auto isSuc = InfomationCurve2DBasical::getCommonData(curInfoList, commonInfo);
            if (!isSuc)
            {
                // TODO 警告
                return;
            }
            m_settings->setCurvePropertyPanelState(commonInfo);
        }

        // 选中状态
        auto model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
        auto selectionModel = m_settings->getCurveNameListView()->selectionModel();
        for (auto row = 0; row < model->rowCount(); row++)
        {
            QStandardItem* item = model->item(row);
            QModelIndex index = model->indexFromItem(item);
            auto isChecked = selectionModel->isSelected(index);
            PolarGraph* graph = qobject_cast<PolarGraph*>(getCurveInfoByItem(item)->getCurveLineAddress());
            graph->setSelected(isChecked);
        }
        m_customPlot->replot();
        slot_updateSelectedGraphState();
    }

    void PolarCoordinateGraphWindow::slot_PolarLinePropertyShow(PolarGraph* plottable, int index)
    {
        // if (plottable == nullptr) {
        //     return;
        // }
        //PolarCoordinateSettingData tmp;

        //auto angularAxis = qobject_cast<QCPPolarAxisAngular*>(m_customPlot->plotLayout()->element(1, 0));
        //if (angularAxis != nullptr)
        //{
        //    // x
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_axisColor = angularAxis->basePen().color();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_axisThickness = angularAxis->basePen().widthF();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_valuePrecision = angularAxis->numberPrecision();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_axisDigitColor = angularAxis->tickLabelColor();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_axisDigitSize = angularAxis->tickLabelFont().pointSize();

        //    // xRange
        //    auto tickerX = dynamic_cast<QCPAxisTickerFixed*>(angularAxis->ticker().data());
        //    if (tickerX != nullptr)
        //    {
        //        if (tickerX->tickStep() == 30)
        //        {
        //            m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_isAutoStepSize = true;
        //        }
        //        else
        //        {
        //            m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_isAutoStepSize = false;
        //        }
        //        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_customStepSize = tickerX->tickStep();
        //    }

        //    // y
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisColor = angularAxis->radialAxis()->basePen().color();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisThickness = angularAxis->radialAxis()->basePen().widthF();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_valuePrecision = angularAxis->radialAxis()->numberPrecision();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisDigitColor = angularAxis->radialAxis()->tickLabelColor();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisDigitSize = angularAxis->radialAxis()->tickLabelFont().pointSize();

        //    // yRange
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoRange = this->GetRadialAutoFlag();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_maxValue = angularAxis->radialAxis()->range().upper;
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_minValue = angularAxis->radialAxis()->range().lower;
        //    auto tickerY = dynamic_cast<QCPAxisTickerFixed*>(angularAxis->radialAxis()->ticker().data());
        //    if (tickerY == nullptr)
        //    {
        //        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoStepSize = true;
        //    }
        //    else
        //    {
        //        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoStepSize = false;
        //        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_customStepSize = tickerY->tickStep();
        //    }

        //    // grid
        //    // tmp.getGrid()->m_isMainGridLineDisplay = angularAxis->grid()->visible();
        //    // tmp.getGrid()->m_mainGridLineColor = angularAxis->grid()->angularPen().color();
        //    // tmp.getGrid()->m_mainGridLineStyle = angularAxis->grid()->angularPen().style() - 1;
        //    // tmp.getGrid()->m_mainGridLineThickness = angularAxis->grid()->angularPen().widthF();

        //    // 网格线
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_isMainGridLineDisplay = angularAxis->grid()->visible();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineColor = angularAxis->grid()->radialPen().color();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineStyle = angularAxis->grid()->radialPen().style() - 1;
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineThickness = angularAxis->grid()->radialPen().widthF();
        //}

        //// title
        //auto title = qobject_cast<QCPTextElement*>(m_customPlot->plotLayout()->element(0, 0));
        //if (title != nullptr)
        //{
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getTitle()->m_titleName = title->text();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getTitle()->m_titleFontColor = title->textColor();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getTitle()->m_titleFontSize = title->font().pointSize();
        //}

        //// legned
        //m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getLegend()->m_legendFontColor = m_customPlot->legend->textColor();
        //m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getLegend()->m_legendFontSize = m_customPlot->legend->font().pointSize();
        //m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getLegend()->m_legendLineColor = m_customPlot->legend->borderPen().color();
        //m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getLegend()->m_legendLineThickness = m_customPlot->legend->borderPen().widthF();

        //if (plottable != nullptr)
        //{
        //    // data
        //    m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty->m_resultDataName = plottable->name();
        //    m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty->m_dataLineColor = plottable->getNormalPen().color();
        //    m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty->m_dataLineStyle = plottable->getNormalPen().style() - 1;
        //    m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty->m_dataLineThickness = plottable->getNormalPen().widthF();
        //    m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty->m_isDisplaySymbol = !plottable->scatterStyle().isNone();
        //    m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty->m_symbolStyle = plottable->scatterStyle().shape() - 1;
        //    m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty->m_symbolSize = plottable->scatterStyle().size() / 2;
        //    m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty->m_symbolColor = plottable->scatterStyle().pen().color();
        //}
        //else
        //{
        //    m_doubleClickPlottable = nullptr;
        //}

        emit IWidgetSignalInstance->signal_exitAddMarkerState();

        if (plottable != nullptr)
        {
            for (auto i : m_addCurveInfo)
            {
                if (plottable == i->getCurveLineAddress())
                {
                    m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty = i->getCurvePropertyData();
                    break;
                }
            }
        //    auto angularAxis = qobject_cast<QCPPolarAxisAngular*>(m_customPlot->plotLayout()->element(1, 0));
        //    // xRange
        //    auto tickerX = dynamic_cast<QCPAxisTickerFixed*>(angularAxis->ticker().data());
        //    if (tickerX != nullptr)
        //    {
        //        if (tickerX->tickStep() == 30)
        //        {
        //            m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_isAutoStepSize = true;
        //        }
        //        else
        //        {
        //            m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_isAutoStepSize = false;
        //        }
        //        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_customStepSize = tickerX->tickStep();
        //    }
        //    // yRange
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoRange = this->GetRadialAutoFlag();
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_maxValue = angularAxis->radialAxis()->range().upper;
        //    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_minValue = angularAxis->radialAxis()->range().lower;
        //    auto tickerY = dynamic_cast<QCPAxisTickerFixed*>(angularAxis->radialAxis()->ticker().data());
        //    if (tickerY == nullptr)
        //    {
        //        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoStepSize = true;
        //    }
        //    else
        //    {
        //        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoStepSize = false;
        //        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_customStepSize = tickerY->tickStep();
        //    }
        }
        else
        {
            m_doubleClickPlottable = nullptr;
            m_polarCoordinateGraphCenterSettingData->m_style2D_DataProperty = nullptr;
        }
        auto _dialog = new PolarCoordinateGraphSettingDialog(this);
        if (nullptr != m_doubleClickPlottable && m_graphs.contains(m_doubleClickPlottable))
        {
            for (auto _curvePair : m_curveMap)
            {
                if (_curvePair.second->getCurveLineAddress() == m_doubleClickPlottable)
                {
                    _dialog->setCurveInfoID(_curvePair.second->getInformationID());
                    break;
                }
            }
            _dialog->setIndexOfGraph(m_graphs.indexOf(m_doubleClickPlottable));
        }
        _dialog->setWindowUniversalID(m_windowUniversalID);
        //connect(_dialog, &PolarCoordinateGraphSettingDialog::pyScriptIsRunning, m_settings, &PolarCoordinateGraphSidebarSettings::setScriptRuning);
        //connect(_dialog, &PolarCoordinateGraphSettingDialog::signal_sendData, this, &PolarCoordinateGraphWindow::slot_ChangePolarLineProperty);
        connect(_dialog, &PolarCoordinateGraphSettingDialog::signal_sendData, [=](int windowUniversalID, int curveInfoID, Info2DPointer info)
            {
                slot_ChangePolarLineProperty(windowUniversalID, curveInfoID, info);
                auto angularAxis = qobject_cast<QCPPolarAxisAngular*>(m_customPlot->plotLayout()->element(1, 0));
                auto tickerX = dynamic_cast<QCPAxisTickerFixed*>(angularAxis->ticker().data());
                m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_maxValue = angularAxis->radialAxis()->range().upper;
                m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_minValue = angularAxis->radialAxis()->range().lower;

                if (m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_isAutoStepSize)
                {
                    m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_customStepSize = 30;//自动步长永远为30
                }

                if (m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoStepSize)
                {
                    auto tickVecs = m_angularAxis->radialAxis()->tickVectorLabels();
                    if (tickVecs.size() > 1)
                    {
                        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_customStepSize = std::abs(tickVecs[0].toDouble() - tickVecs[1].toDouble());
                    }
                }
                /*auto tickerY = dynamic_cast<QCPAxisTickerFixed*>(angularAxis->radialAxis()->ticker().data());*/
                /*m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_customStepSize = tickerY->tickStep();*/
                //m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_customStepSize = tickerX->tickStep();
                _dialog->initData(m_polarCoordinateGraphCenterSettingData);
            });

        if (m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_isAutoStepSize)
        {
            m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_customStepSize = 30;//自动步长永远为30
        }

        if (m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoStepSize)
        {
            auto tickVecs = m_angularAxis->radialAxis()->tickVectorLabels();
            if (tickVecs.size() > 1)
            {
                m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_customStepSize = std::abs(tickVecs[0].toDouble() - tickVecs[1].toDouble());
            }
        }

        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_maxValue = m_angularAxis->radialAxis()->range().upper;
        m_polarCoordinateGraphCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_minValue = m_angularAxis->radialAxis()->range().lower;


        _dialog->initData(m_polarCoordinateGraphCenterSettingData);
        _dialog->ChangeCurrentWidget(index);
        _dialog->showWindow();
    }

    void PolarCoordinateGraphWindow::slot_ChangePolarLineProperty(int windowUniversalID, int curveInfoID, Info2DPointer info, bool bCheckRename)
    {
        PolarCoordinateGraphCenterSettingData* tempPolarCenterSettingData = nullptr;
        if (curveInfoID != -1)
        {
            auto _curveInfo = WindowTotalDataInstance->getInfomationCurve2DBasicalByID(curveInfoID);
            tempPolarCenterSettingData = _curveInfo->getPolarGraphCenterSettingData();
            if (tempPolarCenterSettingData == nullptr)
                return;
        }
        else
        {
            auto _lineChartWindow = (PolarCoordinateGraphWindow*)WindowTotalDataInstance->getGraph2DWindowByID(windowUniversalID);
            tempPolarCenterSettingData = _lineChartWindow->getPolarCoordinateGraphCenterSettingData();
            if (tempPolarCenterSettingData == nullptr)
                return;
        }
        //if (polarCoordinateGraphCenterSettingData == nullptr)
        //{
        //    return;
        //}
        //auto tempPolarCenterSettingData = polarCoordinateGraphCenterSettingData;

        auto angularAxis = qobject_cast<QCPPolarAxisAngular*>(m_customPlot->plotLayout()->element(1, 0));
        if (angularAxis != nullptr)
        {
            // x
            auto basePenX = angularAxis->basePen();
            basePenX.setColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_axisColor);
            basePenX.setWidthF(tempPolarCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_axisThickness);
            angularAxis->setBasePen(basePenX);
            angularAxis->setNumberPrecision(tempPolarCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_valuePrecision);
            angularAxis->setTickLabelColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_axisDigitColor);
            angularAxis->setNumberFormat("f");
            auto tickLabelFontX = angularAxis->tickLabelFont();
            tickLabelFontX.setPointSize(tempPolarCenterSettingData->m_polarCoordinateSettingData->getAngleAxisDisplay()->m_axisDigitSize);
            angularAxis->setTickLabelFont(tickLabelFontX);

            // xRange
            auto tickerX = dynamic_cast<QCPAxisTickerFixed*>(angularAxis->ticker().data());
            if (tickerX != nullptr)
            {
                if (tempPolarCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_isAutoStepSize)
                {
                    tickerX->setTickStep(30);
                }
                else
                {
                    tickerX->setTickStep(tempPolarCenterSettingData->m_polarCoordinateSettingData->getAngleAxisRange()->m_customStepSize);
                }
            }

            // y
            auto basePenY = angularAxis->radialAxis()->basePen();
            basePenY.setColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisColor);
            basePenY.setWidthF(tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisThickness);
            angularAxis->radialAxis()->setBasePen(basePenY);
            angularAxis->radialAxis()->setNumberFormat("f");
            angularAxis->radialAxis()->setNumberPrecision(tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_valuePrecision);
            angularAxis->radialAxis()->setTickLabelColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisDigitColor);
            auto tickLabelFontY = angularAxis->radialAxis()->tickLabelFont();
            tickLabelFontY.setPointSize(tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisDigitSize);
            angularAxis->radialAxis()->setTickLabelFont(tickLabelFontY);

            // yRange
            this->SetRadialAutoFlag(tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoRange);
            if (this->GetRadialAutoFlag())
            {
                angularAxis->radialAxis()->setRange(QCPRange(0, 0.0000001));
                // 此处fit有出现超360度的情况，改为调用自适应槽函数
                /*for (auto curvePair : m_curveMap)
                {
                    auto info = curvePair.second;
                    PolarGraph* graph = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
                    graph->rescaleAxes(true);
                }*/
                angularAxis->radialAxis()->rescale(true);
                slot_adaptiveRange();
            }
            else
            {
                auto rangeY = angularAxis->radialAxis()->range();
                rangeY.upper = tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_maxValue;
                rangeY.lower = tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_minValue;
                angularAxis->radialAxis()->setRange(rangeY);
            }
            if (tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_isAutoStepSize)
            {
                angularAxis->radialAxis()->setTicker(QSharedPointer<QCPAxisTicker>(new QCPAxisTicker()));
            }
            else
            {
                QSharedPointer<QCPAxisTickerFixed> fixed(QSharedPointer<QCPAxisTickerFixed>(new QCPAxisTickerFixed()));
                fixed->setTickStep(tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisRange()->m_customStepSize);
                fixed->setScaleStrategy(QCPAxisTickerFixed::ScaleStrategy::ssNone);
                angularAxis->radialAxis()->setTicker(fixed);
            }

            // 网格颜色
            QPen radialPen = angularAxis->grid()->radialPen();
            radialPen.setColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineColor);
            radialPen.setStyle(Qt::PenStyle(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineStyle + 1));
            radialPen.setWidthF(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineThickness);
            angularAxis->grid()->setRadialPen(radialPen);

            QPen radialSubGridPen = angularAxis->grid()->radialSubGridPen();
            radialSubGridPen.setColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineColor);
            radialSubGridPen.setStyle(Qt::PenStyle(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineStyle + 1));
            radialSubGridPen.setWidthF(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineThickness);
            angularAxis->grid()->setRadialSubGridPen(radialSubGridPen);

            QPen radialZeroLinePen = angularAxis->grid()->radialZeroLinePen();
            radialZeroLinePen.setColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineColor);
            radialZeroLinePen.setStyle(Qt::PenStyle(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineStyle + 1));
            radialZeroLinePen.setWidthF(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineThickness);
            angularAxis->grid()->setRadialZeroLinePen(radialZeroLinePen);

            // 半径轴颜色
            QPen anglePen = angularAxis->grid()->angularPen();
            anglePen.setColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisColor);
            anglePen.setWidthF(tempPolarCenterSettingData->m_polarCoordinateSettingData->getRadiusAxisDisplay()->m_axisThickness);
            angularAxis->grid()->setAngularPen(anglePen);

            // grid
            angularAxis->grid()->setVisible(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_isMainGridLineDisplay);
            auto penGrid = angularAxis->grid()->angularPen();
            penGrid.setColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineColor);
            penGrid.setStyle(Qt::PenStyle(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineStyle + 1));
            penGrid.setWidthF(tempPolarCenterSettingData->m_polarCoordinateSettingData->getGrid()->m_mainGridLineThickness);
            angularAxis->grid()->setAngularPen(penGrid);

            // title
            auto title = qobject_cast<QCPTextElement*>(m_customPlot->plotLayout()->element(0, 0));
            if (title != nullptr)
            {
                title->setText(tempPolarCenterSettingData->m_polarCoordinateSettingData->getTitle()->m_titleName);
                title->setTextColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getTitle()->m_titleFontColor);
                auto fontTitle = title->font();
                fontTitle.setPointSize(tempPolarCenterSettingData->m_polarCoordinateSettingData->getTitle()->m_titleFontSize);
                title->setFont(fontTitle);
            }

            // legend
            m_customPlot->legend->setTextColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getLegend()->m_legendFontColor);
            auto fontLegend = m_customPlot->legend->font();
            fontLegend.setPointSize(tempPolarCenterSettingData->m_polarCoordinateSettingData->getLegend()->m_legendFontSize);
            m_customPlot->legend->setFont(fontLegend);
            auto fontLegendSelected = m_customPlot->legend->selectedFont();
            fontLegendSelected.setPointSize(tempPolarCenterSettingData->m_polarCoordinateSettingData->getLegend()->m_legendFontSize);
            m_customPlot->legend->setSelectedFont(fontLegendSelected);
            auto borderPen = m_customPlot->legend->borderPen();
            borderPen.setColor(tempPolarCenterSettingData->m_polarCoordinateSettingData->getLegend()->m_legendLineColor);
            borderPen.setWidthF(tempPolarCenterSettingData->m_polarCoordinateSettingData->getLegend()->m_legendLineThickness);
            m_customPlot->legend->setBorderPen(borderPen);

            // propertyData
            PolarGraph* plottable = nullptr;
            if (info != nullptr)
                plottable = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
            else
            {
                plottable = m_doubleClickPlottable;
                if (nullptr == m_doubleClickPlottable)
                {
                    if (tempPolarCenterSettingData->m_polarCoordinateSettingData->indexOfGraph >= 0 && tempPolarCenterSettingData->m_polarCoordinateSettingData->indexOfGraph < m_graphs.size())
                    {
                        plottable = dynamic_cast<PolarGraph*>(m_graphs.at(tempPolarCenterSettingData->m_polarCoordinateSettingData->indexOfGraph));
                    }
                }
            }
            if (plottable != nullptr)

            {
                // data

                for (auto curvePair : m_curveMap)
                {
                    auto& info = curvePair.second;
                    PolarGraph* graph = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
                    if (graph == plottable)
                    {
                        if (tempPolarCenterSettingData->m_style2D_DataProperty->m_resultDataName != plottable->name() && bCheckRename)
                        {
                            if (tempPolarCenterSettingData->m_style2D_DataProperty->m_resultDataName.isEmpty())
                            {
                                EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("命名不能为空，请重新编辑。"), EDialogMsg::Error, tr("重命名错误"));
                                tempPolarCenterSettingData->m_style2D_DataProperty->m_resultDataName = plottable->name();
                                return;
                            }
                            auto item = curvePair.first;
                            item->setData(true);
                            item->setText(tempPolarCenterSettingData->m_style2D_DataProperty->m_resultDataName);
                            slot_renameCheck(tempPolarCenterSettingData->m_style2D_DataProperty->m_resultDataName);
                            // plottable->setName(tmp.getDataProperty()->m_resultDataName);
                            // info->setCurveName(tmp.getDataProperty()->m_resultDataName);
                        }
                        break;
                    }
                }

                auto penPlottable = plottable->getNormalPen();
                penPlottable.setColor(tempPolarCenterSettingData->m_style2D_DataProperty->m_dataLineColor);
                penPlottable.setStyle(Qt::PenStyle(tempPolarCenterSettingData->m_style2D_DataProperty->m_dataLineStyle + 1));
                penPlottable.setWidthF(tempPolarCenterSettingData->m_style2D_DataProperty->m_dataLineThickness);
                plottable->setNormalPen(penPlottable);
                auto scatterStyle = plottable->scatterStyle();
                if (tempPolarCenterSettingData->m_style2D_DataProperty->m_isDisplaySymbol)
                {
                    scatterStyle.setShape(QCPScatterStyle::ScatterShape(tempPolarCenterSettingData->m_style2D_DataProperty->m_symbolStyle + 1));
                }
                else
                {
                    scatterStyle.setShape(QCPScatterStyle::ssNone);
                }
                scatterStyle.setSize(tempPolarCenterSettingData->m_style2D_DataProperty->m_symbolSize * 2);
                scatterStyle.setPen(QPen(tempPolarCenterSettingData->m_style2D_DataProperty->m_symbolColor));
                plottable->setScatterStyle(scatterStyle);
            }
        }

        m_customPlot->replot();

        adjustLegendColumns();

        QCoreApplication::processEvents(); // 让 UI 有机会更新,防止获取高度axisRect()->rect().height()失败
        QTimer::singleShot(0, this, [=]() {
            adjustLegendColumns();
            });
    }

    void PolarCoordinateGraphWindow::slot_showHideItemActor(QStandardItem* item)
    {
        if (item == nullptr)
            return;

        const auto& info = getCurveInfoByItem(item);
        auto plottable = info->getCurveLineAddress();

        PolarGraph* graph = qobject_cast<PolarGraph*>(plottable);
        if (!graph)
        {
            return;
        }
        graph->setVisible(item->checkState());
        m_customPlot->replot();
    }

    void PolarCoordinateGraphWindow::slot_updateSelectedGraph()
    {
        // todo
    }

    void PolarCoordinateGraphWindow::slot_removeSelectedGraph()
    {
        disconnect(m_customPlot, &Curve2DPlotor::signal_updateSelectedGraph,
                   this, &PolarCoordinateGraphWindow::slot_updateSelectedGraph);

        auto model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
        auto selectionModel = m_settings->getCurveNameListView()->selectionModel();
        QList<QStandardItem*> removeItemList;
        QList<LineChartTracer*> tracerList;

        for (auto curvePair : m_curveMap)
        {
            auto info = curvePair.second;
            PolarGraph* graph = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
            if (graph->isSelected())
            {
                QModelIndex index = model->indexFromItem(curvePair.first);
                model->removeRow(index.row());

                QList<LineChartTracer*> graphTracerList = graph->getAllTracer();
                graph->removeAllTracer();
                tracerList << graphTracerList;

                info->setCurveLineAddress(nullptr);
                m_angularAxis->removeGraph(graph);
                m_graphs.removeOne(graph);
                removeItemList.append(curvePair.first);
            }
        }
        slot_removeSelectedTracer(tracerList);
        m_customPlot->replot();

        for (auto i : removeItemList)
        {
            auto _infoID = getCurveInfoByItem(i)->getInformationID();
            WindowTotalDataInstance->removeInfomationCurve2DBasicalByID(_infoID);
            removeCurveItemInfoPair(i);
        }
        emit IWidgetSignalInstance->signal_exitAddMarkerState();

        connect(m_customPlot, &Curve2DPlotor::signal_updateSelectedGraph,
                this, &PolarCoordinateGraphWindow::slot_updateSelectedGraph);
    }

    void PolarCoordinateGraphWindow::removeSelectedGraph(const QList<Info2DPointer>& selectedGraphs)
    {
        disconnect(m_customPlot, &Curve2DPlotor::signal_updateSelectedGraph,
                   this, &PolarCoordinateGraphWindow::slot_updateSelectedGraph);

        auto model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
        // auto selectionModel = m_settings->getCurveNameListView()->selectionModel();
        QList<QStandardItem*> removeItemList;
        QList<LineChartTracer*> tracerList;

        for (auto info : selectedGraphs)
        {
            PolarGraph* graph = qobject_cast<PolarGraph*>(info->getCurveLineAddress());

            auto item = getItemFromCurveInfo(info);
            QModelIndex index = model->indexFromItem(item);
            model->removeRow(index.row());

            QList<LineChartTracer*> graphTracerList = graph->getAllTracer();
            graph->removeAllTracer();
            tracerList << graphTracerList;

            m_angularAxis->removeGraph(graph);
            m_graphs.removeOne(graph);
            removeItemList.append(item);
        }
        slot_removeSelectedTracer(tracerList);
        m_customPlot->replot();

        for (auto i : removeItemList)
        {
            auto _infoID = getCurveInfoByItem(i)->getInformationID();
            WindowTotalDataInstance->removeInfomationCurve2DBasicalByID(_infoID);
            removeCurveItemInfoPair(i);
        }

        connect(m_customPlot, &Curve2DPlotor::signal_updateSelectedGraph,
                this, &PolarCoordinateGraphWindow::slot_updateSelectedGraph);
    }

    void PolarCoordinateGraphWindow::slot_copySelectedGraph()
    {
        auto model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
        auto selectionModel = m_settings->getCurveNameListView()->selectionModel();

        auto tempCurveMap = m_curveMap;
        for (auto curvePair : tempCurveMap)
        {
            auto& info = curvePair.second;
            PolarGraph* graph = qobject_cast<PolarGraph*>(info->getCurveLineAddress());

            if (graph->isSelected())
            {
                QString curveName = slot_getCurveName(curvePair.first, curvePair.second);
                Info2DPointer copyInfo = Info2DPointer::create(*info);
                auto item = copyGraph(copyInfo, curveName);
                if (item != nullptr && !curvePair.first->data().isNull() && curvePair.first->data().toBool())
                {
                    item->setData(true);
                }
            }
        }
        slot_updateName();
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
    }

    void PolarCoordinateGraphWindow::slot_removeAlldGraph()
    {
        auto model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
        model->clear();
        QList<LineChartTracer*> tracerList;

        for (auto curvePair : m_curveMap)
        {
            auto info = curvePair.second;
            PolarGraph* graph = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
            tracerList << graph->getAllTracer();
            //graph->removeAllTracer();
            //QCPPolarAxisAngular* axisAngular = graph->keyAxis();
            //axisAngular->removeGraph(graph);
        }

        slot_removeAllTracer(tracerList);

        for (auto curvePair : m_curveMap)
        {
            auto info = curvePair.second;
            PolarGraph* graph = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
            //tracerList << graph->getAllTracer();
            //graph->removeAllTracer();
            QCPPolarAxisAngular* axisAngular = graph->keyAxis();
            axisAngular->removeGraph(graph);
        }

        m_customPlot->clearGraphs();

        m_customPlot->replot();
        m_settings->hideCurvePropertylPanel();

        for (auto info : m_curveMap)
        {
            auto _infoID = info.second->getInformationID();
            WindowTotalDataInstance->removeInfomationCurve2DBasicalByID(_infoID);
        }
        m_curveMap.clear();
        m_graphs.clear();
    }

    void PolarCoordinateGraphWindow::slot_renameGraph()
    {
        auto listView = m_settings->getCurveNameListView();
        QModelIndexList selectedIndexes = listView->selectionModel()->selectedIndexes();
        if (selectedIndexes.size() != 1)
        {
            return;
        }
        listView->setCurrentIndex(selectedIndexes.first());
        listView->edit(selectedIndexes.first());
    }

    void PolarCoordinateGraphWindow::slot_renameCheck(QString name)
    {
        auto listView = m_settings->getCurveNameListView();
        QModelIndexList selectedIndexes = listView->selectionModel()->selectedIndexes();
        if (selectedIndexes.size() != 1)
        {
            return;
        }
        bool success = listView->model()->setData(selectedIndexes.first(), name);
        auto model = (QStandardItemModel*)listView->model();
        auto item = model->itemFromIndex(selectedIndexes.first());
        auto& info = getCurveInfoByItem(item);
        auto graph = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
        for (auto curvePair : m_curveMap)
        {
            auto tmpItem = curvePair.first;
            if (tmpItem == item)
            {
                continue;
            }
            if (item->text() == tmpItem->text())
            {
                EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("当前名称已存在，请重新编辑。"), EDialogMsg::Error, tr("重命名错误"));
                item->setText(graph->name());
                return;
            }
        }

        if (item->text().isEmpty())
        {
            EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("命名不能为空，请重新编辑。"), EDialogMsg::Error, tr("重命名错误"));
            item->setText(graph->name());
            return;
        }

        if (item->text() != graph->name())
        {
            item->setData(true);
            info->setCurveName(name);
            graph->setName(name);
            item->setToolTip(name);
            Style2D_DataProperty* property = info->getCurvePropertyData();
            property->m_resultDataName = name;
        }
        m_customPlot->replot();

        emit IWidgetSignalInstance->signal_exitAddMarkerState();
    }

    void PolarCoordinateGraphWindow::slot_AddTracer()
    {
        auto isShowPreviewTracer = m_customPlot->GetIsShowPreviewTracer();
        if (!isShowPreviewTracer)
        {
            return;
        }

        auto previewTracer = m_customPlot->GetPreviewTracer();
        if (previewTracer == nullptr || !previewTracer->visible())
        {
            return;
        }

        QString name = "Marker" + QString::number(++m_tracerIndex);

        auto existNames = getMarkerNameMap().values();
        for (int i = 0; i < INT_MAX; ++i)
        {
            if (!existNames.contains(name))
            {
                break;
            }
            name = "Marker" + QString::number(++m_tracerIndex);
        }

        int curveInfoID = 0;
        auto _graph = previewTracer->getPolarGraph();
        for (auto _curveInfoPair : m_curveMap)
        {
            if (_curveInfoPair.second->getCurveLineAddress() == _graph)
            {
                curveInfoID = _curveInfoPair.second->getInformationID();
            }
        }

        bool interpolating = previewTracer->interpolating();
        double angle = previewTracer->getGraphAngle();
        int tracerStyle = previewTracer->style();
        double size = previewTracer->size();

        QColor penColor = previewTracer->pen().color();
        int penR = penColor.red();
        int penG = penColor.green();
        int penB = penColor.blue();
        int penA = penColor.alpha();

        QColor brushColor = previewTracer->brush().color();
        int brushR = brushColor.red();
        int brushG = brushColor.green();
        int brushB = brushColor.blue();
        int brushA = brushColor.alpha();

        QStringList _pyCodes{};
        _pyCodes += QString("polarcoordsidebarsettings = PostProcessing.PolarCoordinateGraphSidebarSettings()");
        _pyCodes += QString("polarcoordsidebarsettings.setAddTracer(%1,'%2',%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15,%16)").arg((int)m_windowId).arg(name).arg(angle).arg(tracerStyle).arg(size)
            .arg(penR).arg(penG).arg(penB).arg(penA).arg(brushR).arg(brushG).arg(brushB).arg(brushA).arg(interpolating).arg(curveInfoID).arg(m_tracerIndex);
        emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);

        emit IBaseSignalInstance->signal_polarCoordinateGraphAddTracer((int)m_windowId, name, angle, tracerStyle, size,
            penR, penG, penB, penA, brushR, brushG, brushB, brushA, interpolating, curveInfoID, m_tracerIndex);
    }

    void PolarCoordinateGraphWindow::pyAddTracer(QString name, double angle, int tracerStyle, int size, int penR, int penG, int penB, int penA, 
        int brushR, int brushG, int brushB, int brushA, int interpolating, int curveInfoID, int tracerIndex)
    {
        auto tracer = new LineChartTracer(m_customPlot);
        tracer->setInterpolating(interpolating);
        tracer->setStyle((QCPItemTracer::TracerStyle)tracerStyle);
        tracer->setPen(QColor(penR, penG, penB, penA));
        //tracer->setBrush(QColor(brushR, brushG, brushB, brushA));
        tracer->setSize(size);

        Info2DPointer infoPtr = WindowTotalDataInstance->getInfomationCurve2DBasicalByID(curveInfoID);
        QCPPolarGraph* graph = qobject_cast<QCPPolarGraph*>(infoPtr->getCurveLineAddress());
        qobject_cast<PolarGraph*>(graph)->addTracer(tracer);

        tracer->position->setType(QCPItemPosition::PositionType::ptAbsolute);
        tracer->setGraphAngle(angle);
        tracer->updatePositionOnPolar();
        tracer->setVisible(true);
        tracer->setTracerIndex(tracerIndex);
        tracer->SetName(name);
        tracer->setCurveInfoID(curveInfoID);

        // if (m_tracerPropertyWidget->isHidden())
        // {
        //     QPoint p(0, 0);
        //     if (!m_measureTableWidget->isHidden())
        //     {
        //         p.setX(m_measureTableWidget->width());
        //     }
        //     m_tracerPropertyWidget->move(QPoint(p.x() + kTracerTableWidgetOffsetX, kTracerTableWidgetOffsetY));
        //     m_tracerPropertyWidget->show();
        // }
        setTracerTableWidgetVisible(m_tracerPropertyWidget, true);

        m_tracerPropertyWidget->AppendTracerProperty(tracer);
        auto tmp = tracer->getStyle2DTracerProperty();
        tmp->m_tracerName = tracer->GetName();
        tmp->m_x = tracer->getPolarGraphAngleCoord();
        tmp->m_y = tracer->getPolarGraphRadiusCoord();
        tmp->m_symbolStyle = tracer->style() - 1;
        tmp->m_symbolSize = tracer->size() / 2;
        tmp->m_symbolColor = tracer->pen().color();
        m_customPlot->replot();
    }

    void PolarCoordinateGraphWindow::slot_ShowPreviewTracer(QMouseEvent* event)
    {
        if (!m_customPlot->GetIsShowPreviewTracer())
        {
            return;
        }
        auto previewTracer = m_customPlot->GetPreviewTracer();
        if (previewTracer == nullptr)
        {
            return;
        }

        if (!this->m_angularAxis)
        {
            return;
        }

        const QPointF pos = event->pos();
        QCPPolarGraph* targetGraph = nullptr;
        double distTmp = std::numeric_limits<double>::max();

        QList<QCPPolarGraph*> grahList = m_angularAxis->getGraphList();
        for (auto it = grahList.rbegin(); it != grahList.rend(); ++it)
        {
            auto graph = *it;
            if (!graph->visible())
            {
                continue;
            }
            double dist = graph->selectTest(pos, false);
            if (dist >= 0 && dist < 2.0 && dist < distTmp)
            {
                distTmp = dist;
                targetGraph = graph;
            }
        }

        if (!targetGraph)
        {
            previewTracer->setVisible(false);
            m_customPlot->replot();
            return;
        }

        previewTracer->setVisible(true);
        previewTracer->position->setType(QCPItemPosition::PositionType::ptAbsolute);
        previewTracer->setGraph(nullptr);
        previewTracer->setPolarGraph(targetGraph);

        double angle = 0;
        double radius = 0;
        m_angularAxis->pixelToCoord(pos, angle, radius);
        // if (angle < 0)
        //{
        //     angle += 360.0;
        // }
        previewTracer->setGraphAngle(angle);
        previewTracer->updatePositionOnPolar();
        m_customPlot->replot();
    }

    void PolarCoordinateGraphWindow::slot_removeSelectedTracer(const QList<LineChartTracer*>& selectTracers)
    {        
        for (auto tracer : selectTracers)
        {
            for (int i = 0; i < m_tracerPropertyWidget->rowCount(); ++i)
            {
                auto t = m_tracerPropertyWidget->item(i, 0)->data(QVariant::UserType).value<LineChartTracer*>();
                if (t == tracer)
                {
                    m_tracerPropertyWidget->removeRow(i);
                    break;
                }
            }
            if (m_tracerPropertyWidget->rowCount() == 0)
            {
                // m_tracerPropertyWidget->hide();
                setTracerTableWidgetVisible(m_tracerPropertyWidget, false);

                // if (m_measureTableWidget->isVisible())
                // {
                //     m_measureTableWidget->move(kTracerTableWidgetOffsetX, kTracerTableWidgetOffsetY);
                // }
            }

            for (int i = 0; i < m_measureTableWidget->rowCount(); ++i)
            {
                auto t = m_measureTableWidget->item(i, 0)->data(QVariant::UserType).value<LineChartTracer*>();
                if (t == tracer)
                {
                    m_measureTableWidget->removeRow(i);
                    break;
                }
            }
            if (m_measureTableWidget->rowCount() == 0)
            {
                // m_measureTableWidget->hide();
                setTracerTableWidgetVisible(m_measureTableWidget, false);
            }

            PolarGraph* polarGrah = qobject_cast<PolarGraph*>(tracer->getPolarGraph());
            if (polarGrah)
            {
                polarGrah->removeTracer(tracer);
            }
            m_customPlot->removeItem(tracer);
        }
        m_customPlot->replot();
    }

    void PolarCoordinateGraphWindow::slot_removeSelectedTracer_script(const QList<LineChartTracer*>& selectTracers)
    {
        QList<int> selectTracerIDs;
        for (auto tracer : selectTracers)
        {
            selectTracerIDs.append(tracer->getTracerIndex());
        }

        QString _selectTracerIDs = GlobalHelperInstance->convertIntListToQString(selectTracerIDs);

        QStringList _pyCode;
        _pyCode.append(QString("polarcoordsidebarsettings = PostProcessing.PolarCoordinateGraphSidebarSettings()"));
        _pyCode.append(QString("polarcoordsidebarsettings.setRemoveSelectedTracer(%1,\"%2\",%3)").arg(m_windowId).arg(_selectTracerIDs).arg(selectTracers.front()->getCurveInfoID()));
        emit IBaseSignalInstance->signal_execPYCode(_pyCode, true, false);

        slot_removeSelectedTracer(selectTracers);
    }

    void PolarCoordinateGraphWindow::pyRemoveSelectedTracer(QList<int> selectTracerIDs, int curveInfoID)
    {
        QList<LineChartTracer*> selectTracers;

        Info2DPointer infoPtr = WindowTotalDataInstance->getInfomationCurve2DBasicalByID(curveInfoID);
        if (infoPtr == nullptr)
            return;

        PolarGraph* graph = qobject_cast<PolarGraph*>(infoPtr->getCurveLineAddress());
        auto tracers = graph->getAllTracer();
        for (auto tracer : tracers)
        {
            if (selectTracerIDs.indexOf(tracer->getTracerIndex()) != -1)
            {
                selectTracers.append(tracer);
            }
        }

        slot_removeSelectedTracer(selectTracers);
    }

    void PolarCoordinateGraphWindow::slot_removeAllTracer(const QList<LineChartTracer*>& tracers)
    {
        m_tracerPropertyWidget->clearContents();
        m_tracerPropertyWidget->setRowCount(0);
        m_tracerPropertyWidget->hide();

        m_measureTableWidget->clearContents();
        m_measureTableWidget->setRowCount(0);
        m_measureTableWidget->hide();

        for (auto tracer : tracers)
        {
            m_customPlot->removeItem(tracer);
        }
        m_customPlot->replot();
    }

    void PolarCoordinateGraphWindow::slot_removeAllTracer_script(const QList<LineChartTracer*>& tracers)
    {
        QList<int> tracersCurveInfoID;
        for (auto tracer : tracers)
        {
            if (tracersCurveInfoID.indexOf(tracer->getCurveInfoID()) != -1)
            {
                tracersCurveInfoID.append(tracer->getCurveInfoID());
            }
        }

        QString _tracersCurveInfoID = GlobalHelperInstance->convertIntListToQString(tracersCurveInfoID);

        QStringList _pyCode;
        _pyCode.append(QString("polarcoordsidebarsettings = PostProcessing.PolarCoordinateGraphSidebarSettings()"));
        _pyCode.append(QString("polarcoordsidebarsettings.setRemoveAllTracer(%1,\"%2\")").arg(m_windowId).arg(_tracersCurveInfoID));
        emit IBaseSignalInstance->signal_execPYCode(_pyCode, true, false);

        slot_removeAllTracer(tracers);
    }

    void PolarCoordinateGraphWindow::pyRemoveAllTracer(QList<int> selectTracersCurveInfoID)
    {
        QList<LineChartTracer*> selectTracers;
        for (auto curveInfoID : selectTracersCurveInfoID)
        {
            Info2DPointer infoPtr = WindowTotalDataInstance->getInfomationCurve2DBasicalByID(curveInfoID);
            PolarGraph* graph = qobject_cast<PolarGraph*>(infoPtr->getCurveLineAddress());
            auto tracers = graph->getAllTracer();
            selectTracers << tracers;
        }        

        slot_removeAllTracer(selectTracers);
    }

    void PolarCoordinateGraphWindow::slot_TracerPropertyShow(LineChartTracer* tracer)
    {
        if (tracer == nullptr)
        {
            return;
        }
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto tmp = tracer->getStyle2DTracerProperty();

        //m_doubleClickTracer = tracer;

        auto _dialog = new DialogTracer2DSettings(this);
        _dialog->setTracerID(tracer->getTracerIndex());
        connect(_dialog, &DialogTracer2DSettings::signal_sendData, this, &PolarCoordinateGraphWindow::slot_ChangeTracerProperty);

        QHash<int, QString> map = getMarkerNameMap();
        for (auto it = map.cbegin(); it != map.cend(); ++it)
        {
            if (it.value() == tracer->GetName())
            {
                _dialog->setCurrentMarkerIndex(it.key());
                break;
            }
        }
        _dialog->setExistMarkerMap(map);

        _dialog->ChangeVariableText("角度值");
        _dialog->initData({tmp, nullptr});
        _dialog->ChangeCurrentWidget(0);
        _dialog->showWindow();
    }

    void PolarCoordinateGraphWindow::slot_ChangeTracerProperty(int tracerID, int guideLineID)
    {
        Style2D_TracerProperty* tmp = nullptr;
        for (int i = 0; i < m_tracerPropertyWidget->rowCount(); ++i)
        {
            auto tracer = m_tracerPropertyWidget->item(i, 0)->data(QVariant::UserType).value<LineChartTracer*>();
            if (tracer->getTracerIndex() == tracerID)
            {
                tmp = tracer->getStyle2DTracerProperty();
                if (tmp == nullptr)
                    return;
                tracer->SetName(tmp->m_tracerName);
                tracer->setGraphKey(tmp->m_x);
                tracer->setStyle(QCPItemTracer::TracerStyle(tmp->m_symbolStyle + 1));
                tracer->setSize(tmp->m_symbolSize * 2);
                tracer->setPen(QPen(tmp->m_symbolColor));
                break;
            }
        }

        m_customPlot->replot();

        QStringList _pyCode;
        _pyCode.append(QString("polarcoordsidebarsettings = PostProcessing.PolarCoordinateGraphSidebarSettings()"));
        _pyCode.append(QString("polarcoordsidebarsettings.setChangeTracerProperty(%1,\"%2\",%3,%4,%5,%6,%7,%8,%9,%10)").arg(m_windowId).arg(tmp->m_tracerName).arg(tmp->m_x).arg(tmp->m_symbolStyle).arg(tmp->m_symbolSize)
            .arg(tmp->m_symbolColor.red()).arg(tmp->m_symbolColor.green()).arg(tmp->m_symbolColor.blue()).arg(tmp->m_symbolColor.alpha()).arg(tracerID));
        emit IBaseSignalInstance->signal_execPYCode(_pyCode, true, false);
    }

    void PolarCoordinateGraphWindow::pyChangeTracerProperty(QString name, double x, int symbolStyle, int size, int penR, int penG, int penB, int penA, int tracerID)
    {
        for (int i = 0; i < m_tracerPropertyWidget->rowCount(); ++i)
        {
            auto tracer = m_tracerPropertyWidget->item(i, 0)->data(QVariant::UserType).value<LineChartTracer*>();
            if (tracer->getTracerIndex() == tracerID)
            {
                tracer->SetName(name);
                tracer->setGraphKey(x);
                tracer->setStyle(QCPItemTracer::TracerStyle(symbolStyle + 1));
                tracer->setSize(size * 2);
                tracer->setPen(QPen(QColor(penR, penG, penB, penA)));
                break;
            }
        }

        m_customPlot->replot();
    }

    void PolarCoordinateGraphWindow::slot_polarGraphSelectionChanged(bool selected)
    {
        PolarGraph* graph = qobject_cast<PolarGraph*>(sender());
        if (!graph)
        {
            return;
        }

        for (auto curvePair : m_curveMap)
        {
            if (graph == curvePair.second->getCurveLineAddress())
            {
                QStandardItem* item = curvePair.first;
                QStandardItemModel* model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
                QItemSelectionModel* selectionModel = m_settings->getCurveNameListView()->selectionModel();
                QModelIndex index = model->indexFromItem(item);
                if (selected)
                {
                    if (!selectionModel->isSelected(index))
                    {
                        m_settings->getCurveNameListView()->setCurrentIndex(index);
                        // selectionModel->select(index, QItemSelectionModel::SelectCurrent);
                    }
                }
                else
                {
                    if (selectionModel->isSelected(index))
                    {
                        selectionModel->select(index, QItemSelectionModel::Deselect);
                    }
                }

                break;
            }
        }
    }

    void PolarCoordinateGraphWindow::slot_getSidebarCurveDataSource(QString& dataSource)
    {
        Info2DPointer info = Info2DPointer::create();
        for (const auto& infoTmp : m_curveMap)
        {
            if (infoTmp.second->getCurveName() == dataSource)
            {
                info = infoTmp.second;
                dataSource = info->getDataSources();
                break;
            }
        }
    }

    void PolarCoordinateGraphWindow::slot_updateName()
    {
        auto model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
        for (auto row = 0; row < model->rowCount(); row++)
        {
            QStandardItem* item = model->item(row);
            if (!item->data().isNull() && item->data().toBool())
            {
                continue;
            }

            auto& info = getCurveInfoByItem(item);
            if (info->getIsNewData())
            {
                continue;
            }
            auto reader = info->getReader();
            int index = reader->getRealValueIndex(info->getValueIndex(), info->getValueComponent());
            auto table = reader->getOriginalTable();
            if (index < 0 || index >= reader->getEachColUnitOfValue().size())
            {
                index = 0;
            }
            auto array = table->GetColumn(index + reader->getEachColNameOfKey().size());
            TextArrayMetaStruct metaStruct;
            TextArrayMetaHander::getArrayMeta(array, metaStruct);
            QString valueStr;
            if (metaStruct.resultDataType == 0)
            {
                valueStr = QString("[Re(%1)]").arg(metaStruct.dataGroupName);
            }
            else if (metaStruct.resultDataType == 1)
            {
                valueStr = QString("[Im(%1)]").arg(metaStruct.dataGroupName);
            }
            else if (metaStruct.resultDataType == 2)
            {
                valueStr = QString("[mag(%1)]").arg(metaStruct.dataGroupName);
            }
            else if (metaStruct.resultDataType == 3)
            {
                valueStr = QString("[arg(%1)]").arg(metaStruct.dataGroupName);
            }
            else if (metaStruct.resultDataType == 4)
            {
                valueStr = QString("[%1]").arg(metaStruct.dataGroupName);
            }
            QString name = info->getCurveName().remove(QRegularExpression("\\[.*?]$")) + valueStr;
            QSignalBlocker bl(model);
            item->setText(name);
            item->setToolTip(name);
            qobject_cast<PolarGraph*>(info->getCurveLineAddress())->setName(name);
            info->setCurveName(name);
            info->m_curveSettingData->m_resultDataName = name;
            m_addCurveInfo.append(info);
        }
        m_customPlot->replot();
    }

    QString PolarCoordinateGraphWindow::slot_getCurveName(QStandardItem* item, const Info2DPointer& info)
    {
        QString name;
        if (item == nullptr || info->getCurveLineAddress() == nullptr)
        {
            return name;
        }
        name = info->getCurveName();
        if (!item->data().isNull() && item->data().toBool())
        {
            return name;
        }
        name.remove(QRegularExpression("\\[.*?]$"));
        return name;
    }

    void PolarCoordinateGraphWindow::pyVariableAxisChanged(QList<int> allSelectedItemIndexList, int result, QString variableAxistCurrentText)
    {
        m_settings->pyVariableAxisChanged(allSelectedItemIndexList, result, variableAxistCurrentText);
    }

    void PolarCoordinateGraphWindow::pyAllVariableAxisChanged(QString variableAxistCurrentText)
    {
        m_settings->pyAllVariableAxisChanged(variableAxistCurrentText);
    }

    void PolarCoordinateGraphWindow::pyCurveNameClicked(QList<int> allSelectedItemIndexList)
    {
        m_settings->pyCurveNameClicked(allSelectedItemIndexList);
    }

    void PolarCoordinateGraphWindow::pyCurveNameCheckStateChanged(int index, int checkStatus)
    {
        m_settings->pyCurveNameCheckStateChanged(index, checkStatus);
    }

    void PolarCoordinateGraphWindow::pyDataOperationChanged(bool isNormChecked, bool isDBChecked)
    {
        m_settings->pyDataOperationChanged(isNormChecked, isDBChecked);
    }

    void PolarCoordinateGraphWindow::pyDeleteAllGraph()
    {
        m_settings->deleteAllGraph();
    }

    void PolarCoordinateGraphWindow::pyRenameSelectedGraph(QString name)
    {
        m_settings->renameSelectedGraph(name);
    }

    void PolarCoordinateGraphWindow::pyComplexPartsChanged(bool isAmplitudeChecked, bool isPhaseChecked, bool isRealPartChecked, bool isImaginaryPartChecked)
    {
        m_settings->complexPartsClicked(isAmplitudeChecked, isPhaseChecked, isRealPartChecked, isImaginaryPartChecked);
    }

    void PolarCoordinateGraphWindow::pyFixedValueChanged(QList<int> indexList)
    {
        m_settings->fixedValueChanged(indexList);
    }

    void PolarCoordinateGraphWindow::pyRemoveSelectedGraph(QList<int> indexList)
    {
        m_settings->removeSelectedGraph(indexList);
    }

    void PolarCoordinateGraphWindow::pyCopySelectedGraph()
    {
        m_settings->copySelectedGraph();
    }

    void PolarCoordinateGraphWindow::pyDataOperationChanged(int currentIndex)
    {
        m_settings->pyValueDataChanged(currentIndex);
    }

    void PolarCoordinateGraphWindow::slot_polarCoordinateGraphSaveMainSettingData(int windowUniversalID, int index, QString angDisAxisColor, int angDisAxisThickness, double angDisValuePrecision, QString angDisAxisDigitColor, int angDisAxisDigitSize,
                                                                                  bool angRangIsAutoStepSize, double angRangCustomStepSize,
                                                                                  QString radDisAxisColor, int radDisAxisThickness, double radDisValuePrecision, QString radDisAxisDigitColor, int radDisAxisDigitSize,
                                                                                  bool radRangIsAutoRange, double radRangMaxValue, double radRangMinValue, bool radRangIsAutoStepSize, double radRangCustomStepSize,
                                                                                  bool gridIsMainGridLineDisplay, QString gridMainGridLineColor, int gridMainGridLineStyle, double gridMainGridLineThickness,
                                                                                  QString titleName, QString titleFontColor, int titleFontSize,
                                                                                  QString legendFontColor, int legendFontSize, QString legendLineColor, int legendLineThickness,
                                                                                  QString dataProResultDataName, QString dataProDataLineColor, int dataProDataLineStyle, double dataProDataLineThickness, bool dataProIsDisplaySymbol, int dataProSymbolStyle, double dataProSymbolSize, QString dataProSymbolColor)
    {
        auto _PolarWindow = (PolarCoordinateGraphWindow*)WindowTotalDataInstance->getGraph2DWindowByID(windowUniversalID);
        if (_PolarWindow == nullptr)
            return;
        auto tempData = _PolarWindow->getPolarCoordinateGraphCenterSettingData();
        //PolarCoordinateSettingData* tempData = new PolarCoordinateSettingData(this);
        //auto tempData = m_polarCoordinateGraphCenterSettingData;
        tempData->m_polarCoordinateSettingData->indexOfGraph = index;
        // (angDisAxisColor, angDisAxisThickness, angDisValuePrecision, angDisAxisDigitColor, angDisAxisDigitSize);
        auto _angleAxisDisplay = tempData->m_polarCoordinateSettingData->getAngleAxisDisplay();
        auto colorList = GlobalHelperInstance->convertStringToIntList(angDisAxisColor);
        _angleAxisDisplay->m_axisColor = QColor(colorList[0], colorList[1], colorList[2]);
        _angleAxisDisplay->m_axisThickness = angDisAxisThickness;
        _angleAxisDisplay->m_valuePrecision = angDisValuePrecision;
        colorList = GlobalHelperInstance->convertStringToIntList(angDisAxisDigitColor);
        _angleAxisDisplay->m_axisDigitColor = QColor(colorList[0], colorList[1], colorList[2]);
        _angleAxisDisplay->m_axisDigitSize = angDisAxisDigitSize;
        // (angRangIsAutoStepSize, angRangCustomStepSize);
        auto _angleAxisRange = tempData->m_polarCoordinateSettingData->getAngleAxisRange();
        _angleAxisRange->m_isAutoStepSize = angRangIsAutoStepSize;
        _angleAxisRange->m_customStepSize = angRangCustomStepSize;
        // (radDisAxisColor, radDisAxisThickness, radDisValuePrecision, radDisAxisDigitColor, radDisAxisDigitSize);
        auto _radiusAxisDisplay = tempData->m_polarCoordinateSettingData->getRadiusAxisDisplay();
        colorList = GlobalHelperInstance->convertStringToIntList(radDisAxisColor);
        _radiusAxisDisplay->m_axisColor = QColor(colorList[0], colorList[1], colorList[2]);
        _radiusAxisDisplay->m_axisThickness = radDisAxisThickness;
        _radiusAxisDisplay->m_valuePrecision = radDisValuePrecision;
        colorList = GlobalHelperInstance->convertStringToIntList(radDisAxisDigitColor);
        _radiusAxisDisplay->m_axisDigitColor = QColor(colorList[0], colorList[1], colorList[2]);
        _radiusAxisDisplay->m_axisDigitSize = radDisAxisDigitSize;
        // (radRangIsAutoRange, radRangMaxValue, radRangMinValue, radRangIsAutoStepSize, radRangCustomStepSize);
        auto _radiusAxisRange = tempData->m_polarCoordinateSettingData->getRadiusAxisRange();
        _radiusAxisRange->m_isAutoRange = radRangIsAutoRange;
        _radiusAxisRange->m_maxValue = radRangMaxValue;
        _radiusAxisRange->m_minValue = radRangMinValue;
        _radiusAxisRange->m_isAutoStepSize = radRangIsAutoStepSize;
        _radiusAxisRange->m_customStepSize = radRangCustomStepSize;
        // (gridIsMainGridLineDisplay, gridMainGridLineColor, gridMainGridLineStyle, gridMainGridLineThickness);
        auto _grid = tempData->m_polarCoordinateSettingData->getGrid();
        _grid->m_isMainGridLineDisplay = gridIsMainGridLineDisplay;
        colorList = GlobalHelperInstance->convertStringToIntList(gridMainGridLineColor);
        _grid->m_mainGridLineColor = QColor(colorList[0], colorList[1], colorList[2]);
        _grid->m_mainGridLineStyle = gridMainGridLineStyle;
        _grid->m_mainGridLineThickness = gridMainGridLineThickness;
        // (titleName, titleFontColor, titleFontSize);
        auto _title = tempData->m_polarCoordinateSettingData->getTitle();
        _title->m_titleName = titleName;
        colorList = GlobalHelperInstance->convertStringToIntList(titleFontColor);
        _title->m_titleFontColor = QColor(colorList[0], colorList[1], colorList[2]);
        _title->m_titleFontSize = titleFontSize;
        // (legendFontColor, legendFontSize, legendLineColor, legendLineThickness);
        auto _legend = tempData->m_polarCoordinateSettingData->getLegend();
        colorList = GlobalHelperInstance->convertStringToIntList(legendFontColor);
        _legend->m_legendFontColor = QColor(colorList[0], colorList[1], colorList[2]);
        _legend->m_legendFontSize = legendFontSize;
        colorList = GlobalHelperInstance->convertStringToIntList(legendLineColor);
        _legend->m_legendLineColor = QColor(colorList[0], colorList[1], colorList[2]);
        _legend->m_legendLineThickness = legendLineThickness;
        // (dataProResultDataName, dataProDataLineColor, dataProDataLineStyle, dataProDataLineThickness, dataProIsDisplaySymbol, dataProSymbolStyle, dataProSymbolSize, dataProSymbolColor);
        if (index != -1)
        {
            auto _dataProperty = tempData->m_style2D_DataProperty;
            _dataProperty->m_resultDataName = dataProResultDataName;
            colorList = GlobalHelperInstance->convertStringToIntList(dataProDataLineColor);
            _dataProperty->m_dataLineColor = QColor(colorList[0], colorList[1], colorList[2]);
            _dataProperty->m_dataLineStyle = dataProDataLineStyle;
            _dataProperty->m_dataLineThickness = dataProDataLineThickness;
            _dataProperty->m_isDisplaySymbol = dataProIsDisplaySymbol;
            _dataProperty->m_symbolStyle = dataProSymbolStyle;
            _dataProperty->m_symbolSize = dataProSymbolSize;
            colorList = GlobalHelperInstance->convertStringToIntList(dataProSymbolColor);
            _dataProperty->m_symbolColor = QColor(colorList[0], colorList[1], colorList[2]);

            PolarGraph* tmpPlottable = (PolarGraph*)m_graphs.at(index);
            for (auto& _curvePair : m_curveMap)
            {
                if (_curvePair.second->getCurveLineAddress() == tmpPlottable)
                {
                    slot_ChangePolarLineProperty(m_windowUniversalID, _curvePair.second->getInformationID());
                    break;
                }
            }
        }
        else
        {
            slot_ChangePolarLineProperty(m_windowUniversalID, index);
        }
        //this->slot_ChangePolarLineProperty(tempData);

        
    }

    void PolarCoordinateGraphWindow::updateCurve(QStandardItem* item, Info2DPointer& info)
    {
        auto _graph = info->getGraph();
        auto _reader = info->getReader();
        PolarGraph* curveAdd = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
        auto valueIndex = info->getValueIndex();
        auto componentIndex = info->getValueComponent();
        if (curveAdd == nullptr || _graph == nullptr || _reader == nullptr)
        {
            // TODO 警告
            return;
        }
        _reader->setScanParameterIndex(info->getScanParameterIndex());

        auto otherKeyData = info->getOtherKeyData();
        QVector<QVector<double>> others;
        for (auto i : otherKeyData)
        {
            others.append(QVector<double>{i});
        }
        _reader->setOtherKeyParameter(others);

        QList<Info2DPointer> newInfos;
        QPair<int, int> tem{valueIndex, componentIndex};
        _reader->getChosenLinesFromKey(QList<QPair<int, int>>{tem}, newInfos);
        if (newInfos.size() != 1)
        {
            // TODO 警告， 应该只产生一组数据
            return;
        }

        // 定义一个临时 lambda 函数，用于归一化角度到 [-180, 180]
        auto normalizeAngle = [](QVector<double> angles)
        {
            QVector<double> tmp;
            for (double angle : angles)
            {
                // 先使用 std::fmod 计算 angle 除以 360 后的余数
                double ret = std::fmod(angle, 360.0);
                // 注意：std::fmod 对于负数的余数保留负号
                // 如果余数大于 180，则减去 360，使其进入 [-180, 180] 内
                if (ret > 180.0)
                {
                    ret -= 360.0;
                }
                // 如果余数小于 -180，则加上 360
                else if (ret < -180.0)
                {
                    ret += 360.0;
                }
                tmp.append(ret);
            }
            return tmp;
        };

        auto xData = newInfos[0]->getXData();
        auto yData = newInfos[0]->getYData();

        // qDebug() << "yData =" << yData;
        info->setXData(xData);
        info->setYData(yData);

        int index = _reader->getRealValueIndex(info->getValueIndex(), info->getValueComponent());
        auto table = _reader->getOriginalTable();
        if (index < 0 || index >= _reader->getEachColUnitOfValue().size())
        {
            index = 0;
        }
        auto array = table->GetColumn(index + _reader->getEachColNameOfKey().size());
        TextArrayMetaStruct metaStruct;
        TextArrayMetaHander::getArrayMeta(array, metaStruct);
        bool isPower = false;
        switch (metaStruct.resultParaType)
        {
        case 7:
        case 13:
        case 16:
        case 17:
        case 18:
            isPower = true;
            break;
        default:
            break;
        }

        // TODO 取对数和归一化 针对单条曲线
        normalizeAndLog(yData.second, info->getIsNormalized(), info->getIsDB());

        // 去除取对数后的无效值
        if (info->getIsDB())
        {
            QPair<QString, QVector<double>> targetXData;
            QPair<QString, QVector<double>> targetYData;
            targetXData.second.reserve(xData.second.size());
            targetYData.second.reserve(yData.second.size());

            for (int i = 0; i < yData.second.size(); ++i)
            {
                const double value = yData.second.at(i);
                if (qIsNaN(value) || qIsInf(value))
                {
                    continue;
                }

                targetXData.second.push_back(xData.second.at(i));
                targetYData.second.push_back(value);
            }
            // curveAdd->setData(normalizeAngle(targetXData.second), targetYData.second);
            curveAdd->setData(targetXData.second, targetYData.second);
        }
        else
        {
            // curveAdd->setData(normalizeAngle(xData.second), yData.second);
            curveAdd->setData(xData.second, yData.second);
        }

        // curveAdd->setName(yData.first);
        // item->setText(yData.first);

        // curveAdd->rescaleAxes(true);

        // if (m_angularAxis != nullptr)
        //{
        // m_angularAxis->rescale(true);
        //}
        // m_customPlot->rescaleAxes(true);

        slot_adaptiveRange();
        // m_customPlot->replot();
    }

    void PolarCoordinateGraphWindow::measureData(MeasureType type)
    {
        if (!m_angularAxis)
        {
            return;
        }
        const QString measureName = getMeasureTypeName(type);

        const QList<QCPPolarGraph*> graphList = m_angularAxis->getGraphList();
        for (QCPPolarGraph* graph : graphList)
        {
            PolarGraph* polarGraph = qobject_cast<PolarGraph*>(graph);
            if (!polarGraph->isSelected())
            {
                continue;
            }

            const auto& graphData = polarGraph->data();
            bool findRange = false;
            auto range = graphData->valueRange(findRange);
            if (!findRange)
            {
                continue;
            }

            bool isExits = false;
            for (int i = 0; i < m_measureTableWidget->rowCount(); ++i)
            {
                auto t = m_measureTableWidget->item(i, 0)->data(QVariant::UserType).value<LineChartTracer*>();
                if (t->getPolarGraph() == graph && t->GetName() == measureName)
                {
                    isExits = true;
                    break;
                }
            }
            if (isExits)
            {
                EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("%1上该测量已存在").arg(graph->name()), EDialogMsg::Warning, tr("测量提示"));
                continue;
            }

            bool isBeamBandwidthTracer(false);
            LineChartTracer* tracer = nullptr;
            if (measureName == "最大值")
            {
                tracer = new LineChartTracer(m_customPlot);
                tracer->SetName("最大值");
                tracer->setVisible(true);
            }
            else if (measureName == "最小值")
            {
                tracer = new LineChartTracer(m_customPlot);
                tracer->SetName("最小值");
                tracer->setVisible(true);
            }
            else if (measureName == "平均值")
            {
                tracer = new LineChartTracer(m_customPlot);
                tracer->SetName("平均值");
                tracer->setVisible(false);
            }
            else if (measureName == "半功率波束带宽")
            {
                auto t = new BeamBandwidthTracer(m_customPlot);
                t->SetName("半功率波束带宽");
                t->setVisible(false);//先设为不可见，后面判断计算成功的才显示
                QCPItemLine* indicator = t->GetIndicator();
                indicator->start->setType(QCPItemPosition::PositionType::ptAbsolute);
                indicator->end->setType(QCPItemPosition::PositionType::ptAbsolute);
                tracer = t;
                isBeamBandwidthTracer = true;
            }

            if (tracer)
            {
                tracer->position->setType(QCPItemPosition::PositionType::ptAbsolute);
                polarGraph->addTracer(tracer);
                tracer->SetLayerable(graph);

                auto rowCount = m_measureTableWidget->rowCount();
                if (rowCount == 0 && isBeamBandwidthTracer)
                {
                    setTracerTableWidgetVisible(m_measureTableWidget, false);
                }
                else
                {
                    setTracerTableWidgetVisible(m_measureTableWidget, true);
                }
                m_measureTableWidget->AppendTracerProperty(tracer);
            }
            for (auto _curveInfoPair : m_curveMap)
            {
                if (_curveInfoPair.second->getCurveLineAddress() == graph)
                {
                    tracer->setCurveInfoID(_curveInfoPair.second->getInformationID());
                }
            }
        }

        m_customPlot->replot();
    }

    void PolarCoordinateGraphWindow::setTracerTableWidgetVisible(QTableWidget* widget, bool visible)
    {
        if (widget == m_tracerPropertyWidget)
        {
            if (visible)
            {
                m_tracerPropertyWidget->move(kTracerTableWidgetOffsetX, kTracerTableWidgetOffsetY);
            }

            if (m_measureTableWidget->isVisible())
            {
                QPoint pos(kTracerTableWidgetOffsetX, kTracerTableWidgetOffsetY);
                if (visible)
                {
                    pos.rx() += m_tracerPropertyWidget->width() + kTracerTableWidgetOffsetX;
                }
                m_measureTableWidget->move(pos);
            }
        }
        else if (widget == m_measureTableWidget)
        {
            if (visible)
            {
                QPoint pos(kTracerTableWidgetOffsetX, kTracerTableWidgetOffsetY);
                if (m_tracerPropertyWidget->isVisible())
                {
                    pos.rx() += m_tracerPropertyWidget->width() + kTracerTableWidgetOffsetX;
                }
                m_measureTableWidget->move(pos);
            }
        }

        if (visible)
        {
            widget->show();
        }
        else
        {
            widget->hide();
        }
    }

    void PolarCoordinateGraphWindow::slot_updateBeamBandwidthProperty()
    {
        //if (m_measureTableWidget->isHidden())
        //{
        //    return;
        //}
        QList<int> toDeleteIndexList;
        QList<LineChartTracer*> toDeleteTracerList;
        QStringList errorList;
        LineChartTracer* tracer = nullptr;
        for (int i = 0; i < m_measureTableWidget->rowCount(); ++i)
        {
            tracer = m_measureTableWidget->item(i, 0)->data(QVariant::UserType).value<LineChartTracer*>();
            auto graph = tracer->getPolarGraph();
            if (graph == nullptr)
            {
                continue;
            }
            const auto& graphData = graph->data();
            bool findRange = false;
            auto range = graphData->valueRange(findRange);
            std::set<double> maxKeySet;
            double value = 0;
            if (!findRange)
            {
                continue;
            }
            if (tracer->GetName() != getMeasureTypeName(MeasureType::HalfPowerBeamWidth))
            {
                continue;
            }

            BeamBandwidthTracer* halfPowerTracer  = qobject_cast<BeamBandwidthTracer*>(tracer);
            if (halfPowerTracer == nullptr)
            {
                continue;
            }

            auto isVisible = tracer->GetLabel()->visible();
            if (halfPowerTracer->isMeasured())
            {
                tracer->setVisible(graph->visible()); //同步可见性，测量成功的才显示，失败的会删除
                if (!tracer->visible())
                {
                    continue;
                }
            }

            bool isDb = false;
            for (auto curvePair : m_curveMap)
            {
                auto& info = curvePair.second;
                if (info->getCurveLineAddress() == graph)
                {
                    isDb = info->getIsDB();
                    break;
                }
            }
            if (isDb)
            {
                value = range.upper - 3;
            }
            else
            {
                value = range.upper * 0.707;
            }

            if (!range.contains(value))//测量失败
            {
                tracer->setVisible(false);
                EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("%1不满足半功率波束带宽测量条件").arg(graph->name()), EDialogMsg::Warning, tr("测量提示"));

                if (isVisible)
                {
                    errorList.append(graph->name());
                }
                toDeleteIndexList.append(i);
                toDeleteTracerList.append(tracer);
                continue;
            }
            else //测量成功
            {
                tracer->setVisible(graph->visible()); //同步可见性，测量成功的才显示，失败的会删除
                halfPowerTracer->setIsMeasured(true);

                // 以下代码调整到标记Marker20250923
                //for (int i = 0; i < m_measureTableWidget->rowCount(); i++)
                //{
                //    if(m_measureTableWidget->item(i,0)->data(QVariant::UserType).value<LineChartTracer*>() == tracer)
                //    {
                //        m_measureTableWidget->showRow(i);
                //        break;
                //    }
                //}
                // 以上代码调整到标记Marker20250923
            }

            for (auto iter = graphData->begin(); iter != graphData->end(); ++iter)
            {
                if (qFuzzyCompare(iter->value, range.upper))
                {
                    maxKeySet.insert(iter->key);
                }
            }
            QVector<QPair<QCPRange, QCPRange>> rangeArray;
            for (auto iter = graphData->begin(); iter != graphData->end(); ++iter)
            {
                const auto& previousIter = iter; // 前一个原始数据点
                const auto& nextIter = iter + 1; // 后一个原始数据点
                QCPRange keyRange, valueRange;
                if (nextIter != graphData->end())
                {
                    keyRange.lower = previousIter->key;
                    keyRange.upper = nextIter->key;
                    valueRange.lower = previousIter->value;
                    valueRange.upper = nextIter->value;
                }
                else
                {
                    keyRange.upper = keyRange.lower = previousIter->key;
                    valueRange.upper = valueRange.lower = previousIter->value;
                }
                bool isContains = false;
                if (valueRange.lower > valueRange.upper)
                {
                    if (value >= valueRange.upper && value <= valueRange.lower)
                    {
                        isContains = true;
                    }
                }
                else
                {
                    if (value >= valueRange.lower && value <= valueRange.upper)
                    {
                        isContains = true;
                    }
                }
                if (isContains)
                {
                    rangeArray.append(qMakePair(keyRange, valueRange));
                }
            }
            std::set<double> keySet;
            for (int j = 0; j < rangeArray.size(); ++j)
            {
                auto& range = rangeArray.at(j);
                double key = std::numeric_limits<double>::quiet_NaN();
                if (range.first.upper == range.first.lower)
                {
                    key = range.second.lower;
                }
                else
                {
                    double k = (range.second.upper - range.second.lower) / (range.first.upper - range.first.lower);
                    key = range.first.lower + (value - range.second.lower) / k;
                }
                if (std::isnan(key))
                {
                    continue;
                }
                else
                {
                    keySet.insert(key);
                }
            }
            if (keySet.size() < 2)
            {
                tracer->setVisible(false);
                if (isVisible)
                {
                    errorList.append(graph->name());
                }
                continue;
            }
            bool isContains = false;
            for (double maxKey : maxKeySet)
            {
                // auto iter = keySet.begin();
                //++iter;
                for (auto iter = ++keySet.begin(); iter != keySet.end(); ++iter)
                {
                    auto it = iter;
                    const auto& previousIter = --it; // 前一个原始数据点
                    const auto& nextIter = iter;     // 后一个原始数据点
                    if (*previousIter < maxKey && *nextIter > maxKey)
                    {
                        auto indeicator = qobject_cast<BeamBandwidthTracer*>(tracer)->GetIndicator();
                        QPointF startPos = graph->coordsToPixels(*previousIter, value);
                        indeicator->start->setPixelPosition(startPos);
                        QPointF endPos = graph->coordsToPixels(*nextIter, value);
                        indeicator->end->setPixelPosition(endPos);

                        tracer->position->setCoords(*previousIter, value);
                        tracer->updatePositionOnPolar();
                        isContains = true;
                        break;
                    }
                }
            }
            // isContains为false，表明测量失败，需要弹窗提示和添加到删除队列
            if (!isContains)
            {
                tracer->setVisible(false);
                toDeleteTracerList.append(tracer);
                EDialogMsgResult _result = IdaDialogMsg::showDialog(this, QString("%1不满足半功率波束带宽测量条件").arg(graph->name()), EDialogMsg::Warning, tr("测量提示"));
                if (isVisible)
                {
                    errorList.append(graph->name());
                }
                continue;
            }
            // 代码标记Marker20250923
            // 最后将tracer刷新显示出来
            for (int i = 0; i < m_measureTableWidget->rowCount(); i++)
            {
                if (m_measureTableWidget->item(i, 0)->data(QVariant::UserType).value<LineChartTracer*>() == tracer)
                {
                    m_measureTableWidget->showRow(i);
                    break;
                }
            }
        }

        //删除测量不成功的半功率波束tracer
        slot_removeSelectedTracer(toDeleteTracerList);
        // if (!errorList.isEmpty()) {
        //     EDialogMsgResult _result = IdaDialogMsg::showDialog(this, errorList.join("\n"), EDialogMsg::Error, tr("半功率波束带宽错误列表"));
        // }
    }

    void PolarCoordinateGraphWindow::slot_updateSelectedGraphState()
    {
        QList<Info2DPointer> curInfoList;

        auto model = qobject_cast<QStandardItemModel*>(m_settings->getCurveNameListView()->model());
        auto selectionModel = m_settings->getCurveNameListView()->selectionModel();
        for (auto curvePair : m_curveMap)
        {
            auto info = curvePair.second;
            if (info->getCurveLineAddress() == nullptr)
            {
                continue;
            }
            PolarGraph* graph = qobject_cast<PolarGraph*>(info->getCurveLineAddress());
            if (graph->isSelected())
            {
                curInfoList.append(info);
            }
        }

        int state = 0;
        // 设置框中选中的曲线发生改变->根据曲线信息更新m_settings
        if (!curInfoList.isEmpty())
        {
            state = 1;
            QString dataSources;
            for (const auto& info : curInfoList)
            {
                const auto& str = info->getDataSources();
                if (dataSources.isEmpty())
                {
                    dataSources = str;
                }
                else if (dataSources != str)
                {
                    dataSources.clear();
                    break;
                }
            }
            if (!dataSources.isEmpty())
            {
                // 方向图数据，且变量为theta/phi角度时才可启用 半功率波束宽度
                if (dataSources.contains("方向图数据"))
                {
                    auto info = curInfoList.at(0);
                    const auto& str = info->getReader()->getEachColNameOfKey().at(info->getScanParameterIndex());
                    if (str.toUpper() == "THETA" || str.toUpper() == "PHI")
                    {
                        state = 2;
                    }
                }
                else if (dataSources.contains("驻波比数据"))
                {
                    state = 3;
                }
            }
        }
        emit signal_updateMeasureButtonState(state);
    }

    void PolarCoordinateGraphWindow::slot_changeAllCurveVariableAxis(const QString& newVariableAxisName)
    {

        for (auto dataInfo : m_curveMap)
        {
            // 对所有选择的数据单独处理
            auto _graph = dataInfo.second->getGraph();
            auto _reader = dataInfo.second->getReader();
            auto* curveAdd = dataInfo.second->getCurveLineAddress();

            if (curveAdd == nullptr || _graph == nullptr || _reader == nullptr)
            {
                // TODO 警告
                return;
            }

            // auto changedScanName = changedInfo.getScanParameterName();
            auto keyNames = _reader->getEachColNameOfKey();
            int newScanIndex = keyNames.indexOf(newVariableAxisName);
            // 设置新的扫描参数
            if (newScanIndex == -1)
            {
                // TODO 警告
                continue;
            }

            auto oldScanIndex = dataInfo.second->getScanParameterIndex();
            auto keyDataList = _reader->getEachColDataOfKey();
            dataInfo.second->setScanParameterIndex(newScanIndex);
            _reader->setScanParameterIndex(newScanIndex);

            // 设置新的otherKeyList
            QVector<double> otherKeyVector = dataInfo.second->getOtherKeyData();
            otherKeyVector.insert(oldScanIndex, keyDataList[oldScanIndex][0]);
            otherKeyVector.removeAt(newScanIndex);
            QVector<QVector<double>> tempOtherKey;
            for (auto i : otherKeyVector)
            {
                tempOtherKey.append(QVector<double>{i});
            }
            _reader->setOtherKeyParameter(tempOtherKey);
            dataInfo.second->setOtherKeyData(otherKeyVector);

            QPair<int, int> tem{dataInfo.second->getValueIndex(), dataInfo.second->getValueComponent()};
            QList<Info2DPointer> newYList;
            _reader->getChosenLinesFromKey(QList<QPair<int, int>>{tem}, newYList);

            updateCurve(dataInfo.first, dataInfo.second);
        }
        QList<QStandardItem*> items;
        for (auto curvePair : m_curveMap)
        {
            items.append(curvePair.first);
        }
        slot_chosenItemsChanged(items);
    }

    void PolarCoordinateGraphWindow::slot_closeTree(const QList<QStandardItem*>& items)
    {
        QList<Info2DPointer> itemToDelete;
        for (auto treeItem : items)
        {
            for (auto info : m_curveMap)
            {
                if (info.second->getProjectTreeSourceItem() == treeItem)
                {
                    QCPGraph* graph = qobject_cast<QCPGraph*>(info.second->getCurveLineAddress());
                    itemToDelete.append(info.second);
                }
            }
        }
        removeSelectedGraph(itemToDelete);
    }

    QHash<int, QString> PolarCoordinateGraphWindow::getMarkerNameMap()
    {
        QHash<int, QString> map;
        for (int i = 0; i < m_tracerPropertyWidget->rowCount(); ++i)
        {
            auto t = m_tracerPropertyWidget->item(i, 0)->data(QVariant::UserType).value<LineChartTracer*>();
            map.insert(i, t->GetName());
        }
        return map;
    }

    void PolarCoordinateGraphWindow::slot_exportMarkerData()
    {
        QString fileName = m_tracerPropertyWidget->exportDatas();

        QStringList _pyCode;
        _pyCode.append(QString("polarcoordsidebarsettings = PostProcessing.PolarCoordinateGraphSidebarSettings()"));
        _pyCode.append(QString("polarcoordsidebarsettings.setExportMarkerData(%1,'%2')").arg(m_windowId).arg(fileName));
        emit IBaseSignalInstance->signal_execPYCode(_pyCode, true, false);
        //emit IBaseSignalInstance->signal_polarCoordinateGraphExportMarkerData(m_windowId);
    }

    void PolarCoordinateGraphWindow::pyExportMarkerData(QString fileName)
    {
        m_tracerPropertyWidget->setFileName(fileName);
        m_tracerPropertyWidget->exportDatas();
    }


} // namespace pst
